javascript regex function [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to write JS regex (or function) that tells me if a string is in that format:
/root/:param1/:param2/:param3/.../
OR
/root/:param1/:param2/:param3/... (without last slash)
Any ideas?
Thanks.

If I'm interpreting your question correctly, it looks like we can break this pattern down into three primary components:
Start with /root
Followed by some number of /:param
Optionally followed by a /
Now we just need to develop the regular expressions for each component and combine them:
Start with /root
Start of the string is marked by ^ and we follow with /root
^/root
Followed by some number of /:param:
Let's say :param should match 1-N characters (+ operator) that are not a forward slash [^/]
This gives us /[^/]+
0-N of this entire unit can be matched using groups and the * operator: (/[^/]+)*
Optionally followed by a /
Use the ? operator: /?
Append a $ to specify the string's end
All together we get the regular expression ^/root(/[^/]+)*/?$. You can use RegExp.prototype.test to check for matches:
r = new RegExp('^/root(/[^/]+)*/?$')
r.test('/root') // => true
r.test('/root/') // => true
r.test('/root/apple/banana') // => true
r.test('/root/zebra/monkey/golf-cart/') // => true
If you're looking to match a URL path segment you'll need to use a more specific character set instead of the [^/] I used here for :param characters.

Related

Is there way to change a substring in js? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Improve this question
I have a string like:
def definition():
I want to change word def (for example), every instance of word def but not the "def"s that are part of other words
like this
console.log("def definition():".specialReplace("def", "abc"));
and result should be
abc definition():
not
abc abcinition():
Use String#replace or String#replaceAll with a regular expression:
const specialReplace = (str) => str.replaceAll(/\bdef\b/g, 'abc')
console.log(specialReplace("def definition")) // abc definition
console.log(specialReplace("def definition def")) // abc definition abc
In the regular expression, \b is a boundary type assertion that matches any word boundary, such as between a letter and a space.
Note that the same sequence \b is also used inside character class regular expression positions ([\b]), to match the backspace character.

using regex in javascript to check if foreign characters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to create a simple function that checks if there are foreign characters in my string. Essentially, this is what I'm trying to get:
var str_1 = "отправка.py" // should return true
var str_2 = "bla.py" // should return false
var str_3 = "bla23.py" // should return false
var str_4 = "bla23_.py" // should return false
I want to make sure that there aren't any foreign characters, while still making sure that I allow everything else (characters like "_", "-", ...).
I'm just trying to avoid the Russian, Mandarin, etc.. alphabets.
You are looking only for ASCII. So something like:
!/^[\x00-\x7F]*$/.test('отправка.py'); // => true
!/^[\x00-\x7F]*$/.test('bla.py'); // => false
Code
See regex in use here
[^ -~]
Alternatively: [^\x00-\x7F] (which seems to have already been posted by #BlakeSimpson)
Usage
const r = /[^ -~]/
const a = [
"отправка.py",
"bla.py",
"bla23.py",
"bla23_.py"
]
a.forEach(function(s) {
if(r.exec(s) !== null) {
console.log(s)
}
})
Explanation
[^ -~] Matches everything that's not from the space character (DEC 32) to the tilde ~ symbol (DEC 126) - which are all the visible ASCII characters.
Also, note that I don't use the g modifier. This is intentional as the OP is only asking to check whether or not there are foreign characters in the string. That means that so long as 1 character exists in the string that meet those requirements it should be matched (no need to match more than one).

Regex to evaluate a list of 6 digit numbers separated by commas [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have an input field that I would like users to put in a list of numbers that are 6 digits long. the list the users input will have variable lengths.
Pass
123456, 123457, 156545, 546541, 546541
Pass
123456, 123457
Pass
546541
Fail
12345, 155154
Fail
154s54, 159475, 153456
Fail
154s544, 159475, 153456
The regEx you are looking for is /^\d{6}$/, which matches a 6 digit number and only 6 digit number.
var cases = [
'123456, 123457, 156545, 546541, 546541',
'123456, 123457',
'546541',
'12345, 155154',
'154s54, 159475',
'154s544, 159475, 153456'
];
//Break up numbers in string into array the check each token
//against the regex. If all tokens passes the test, then it
//returns true, else false.
t = cases.map(c => c.split(', ')
.reduce((p, n) => p && !!n.match(/^\d{6}$/), true));
for (let i=0; i < cases.length;i++)
console.log('case:', cases[i], t[i]?'pass':'fail');
Assuming that you are not looking to capture the individual numbers, but just want to validate the input, the following regex should do:
^(\d{6},\s*)*\d{6}$
Breakdown of the regex:
^ beginning of the string
(\d{6},\s*)* zero or more occurrences of a 6-digit number, followed by a comma and optional whitespace
\d{6} a 6-digit number (this is the last and possibly the only one)
$ end of the string
Note that the expression enclosed within parentheses is a capture group. To avoid capture and make it stricter the expression would be written as:
^(?:\d{6},\s*)*\d{6}$
Note the ?: after the first parenthesis. It means match the expression but do not capture it.

Regex pattern Alphanumeric and dollar sign [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to know how I set a regex pattern for aphanumeric and dollar sign.
Except for dollar sign, it does not accept any other special characters.
Here are examples...
The pattern should be okay with ....
hahah
hohho
hihihi
$hahah
hahah I will get $100 for this
The pattern should be sad with ....
hi James.
#fdasfdas
run!
Any idea?
so you want it to require a '$' symbol somewhere in the string? – yes.
Do you want to allow spaces also? - yes
please add more details, unless the below answer is what you are looking for. Currently this isn't a clear question. – sorry I just got back to my machine.
public static bool IsAlphanumericCharactersAndDollarSign(string str)
{
if (str == null) return false;
Regex rg = new Regex(#"/[a-zA-z0-9\s\$]*/");
return rg.IsMatch(str);
}
Pattern for this: /[a-zA-z0-9\s\$]*/ match alphanumeric, spaces and $ sign 0 or more times
This is PCRE compliant, but in perl for example you need to escape the $ with \$

about complicated RegExp [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need a regexp to check the String "incould \w,-,. and not start with ."
I hope the result is
abc ->false
ab_c ->false
a-b_c.->false
a#-b_C. ->true
.a-b_c. ->true
I tried /[^\w-\.]/ only ".a-b_c." was fail, I get false (I hope be true)
and I tried /^\./ can be ".a-b_c." true, but other was fail.
has any body can help me?
If you need to match string including only \w, - or . and not starting with ., then try this:
/^(?!\.)[\w.-]+$/
Details:
^ - search from start of string
(?!\.) - don't match if there is . symbol at this position
[\w.-]+ - match to more than 1 symbols from \w.- set
$ - match to end of string
Testing:
abc -> matched
ab_c -> matched
a-b_c. -> matched
a#-b_C. -> not matched
.a-b_c. -> not matched

Categories