How do I match a number inside square brackets with regex - javascript

I wrote a regular expression which I expect should work but it doesn't.
var regex = new RegExp('(?<=\[)[0-9]+(?=\])')
JavaScript is giving me the error:
Invalid regular expression :(/(?<=[)[0-9]+(?=])/): Invalid group
Does JavaScript not support lookahead or lookbehind?

This should work:
var regex = /\[[0-9]+\]/;
edit: with a grouping operator to target just the number:
var regex = /\[([0-9]+)\]/;
With this expression, you could do something like this:
var matches = someStringVar.match(regex);
if (null != matches) {
var num = matches[1];
}

Lookahead is supported, but not lookbehind. You can get close, with a bit of trickery.

To increment multiple numbers in the form of lets say:
var str = '/a/b/[123]/c/[4567]/[2]/69';
Try:
str.replace(/\[(\d+)\]/g, function(m, p1){
return '['+(p1*1+1)+']' }
)
//Gives you => '/a/b/[124]/c/[4568]/[3]/69'

If you're quoting a RegExp, watch out for double escaping your backslashes.

Related

Javascript RegEx to match a part of a string [duplicate]

What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.
For example, if I'm trying to match for abc, then 1abc1, 1abc, and abc1 would not match.
Use the start and end delimiters: ^abc$
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b (word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';
var pat = /\b(abc)\b/g;
console.log(str.match(pat));
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Simple regex replace brackets

Is there an easy way to make this string:
(53.5595313, 10.009969899999987)
to this String
[53.5595313, 10.009969899999987]
with JavaScript or jQuery?
I tried with multiple replace which seems not so elegant to me
str = str.replace("(","[").replace(")","]")
Well, since you asked for regex:
var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[$1]");
// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");
...but that's kind of complicated. You could just use .slice():
var output = "[" + input.slice(1,-1) + "]";
For what it's worth, to replace both ( and ) use:
str = "(boob)";
str = str.replace(/[\(\)]/g, ""); // yields "boob"
regex character meanings:
[ = start a group of characters to look for
\( = escape the opening parenthesis
\) = escape the closing parenthesis
] = close the group
g = global (replace all that are found)
Edit
Actually, the two escape characters are redundant and eslint will warn you with:
Unnecessary escape character: ) no-useless-escape
The correct form is:
str.replace(/[()]/g, "")
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
This Javascript should do the job as well as the answer by 'nnnnnn' above
stringObject = stringObject.replace('(', '[').replace(')', ']')
If you need not only one bracket pair but several bracket replacements, you can use this regex:
var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
var output = input.replace(/\((.+?)\)/g, "[$1]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234]

Why this regex is causing infinity loop?

function listPlayers(subject){
var players=[];
var myregexp = /(\S*)(?:,\s|$)/g;
var match = myregexp.exec(subject);
while (match != null) {
players.push(match[1]);
match = myregexp.exec(subject);
}
return players;
}
The string I'm trying to match is like this �r Henderson�r�f, Pedrin�r�f, �c~�lArthur�r�f, John�r�f
The output I expect is an array like this ['Henderson�r�f', 'Pedrin�r�f', '�c~�lArthur�r�f', 'John�r�f']
What I don't understand is on regex buddy everything seems ok.
Try changing the regexp to:
var myregexp = /(\S+)(?:,\s|$)/g;
I think the loop may be because it repeatedly matches an empty string at the end.
Since I don't think you're interested in getting zero-length names, this is probably a better regexp in general.
Just for interest, a perhaps simpler way using a zero-width positive lookahead assertion:
function listPlayers( subject ) {
return subject.match( /\S+(?=,\s|$)/g );
}

Trouble getting my regular expression to match

I am having some trouble with my regex in javascript.
I have the following code, that I think should match, but it doesn't.
var rgx = new RegExp("{\d+:(\d+)}");
if (rgx.test("{0:00000}") == true) {
alert("match");
}
else
{
alert("no match");
}
​I am unsure if I should use test() here. I really want to catch the group, in my regex but exec() seems to give me the same result.
So what am I doing wrong?
The problem is that you need to escape the \ character in your regex:
var rgx = new RegExp("{\\d+:(\\d+)}");
Alternatively, you can use the literal syntax:
var rgx = /{\d+:(\d+)}/;
To capture the results, you should also use the .match function as opposed to test or exec. It will return null if it doesn't match and an array of at least one element if it does match.
There are multiple issues with the regex:
var rgx = new RegExp("{\d+:(\d+)}");
First (first noted by syazdani), you must string-escape the backslashes:
var rgx = new RegExp("{\\d+:(\\d+)}");
or better yet use a regex literal:
var rgx = /{\d+:(\d+)}/
Second, { and } have a special meaning in regex and should be escaped:
var rgx = /\{\d+:(\d+)\}/
Third, as noted by Ian, you might want to ensure the entire string is matched:
var rgx = /^\{\d+:(\d+)\}$/
RegExp#test returns a boolean true/false whether the string matches.
RegExp#exec returns an array holding the match and all captured groups if the string is matched, or null if the string is not matched:
var matches = /\{\d+:(\d+)\}/.exec("{0:000000}");
if(matches){
console.log(matches[1]); //logs "000000"
}

Javascript split function not correct worked with specific regex

I have a problem. I have a string - "\,str\,i,ing" and i need to split by comma before which not have slash. For my string - ["\,str\,i", "ing"]. I'm use next regex
myString.split("[^\],", 2)
but it's doesn't worked.
Well, this is ridiculous to avoid the lack of lookbehind but seems to get the correct result.
"\\,str\\,i,ing".split('').reverse().join('').split(/,(?=[^\\])/).map(function(a){
return a.split('').reverse().join('');
}).reverse();
//=> ["\,str\,i", "ing"]
Not sure about your expected output but you are specifying string not a regex, use:
var arr = "\,str\,i,ing".split(/[^\\],/, 2);
console.log(arr);
To split using regex, wrap your regex in /..../
This is not easily possible with js, because it does not support lookbehind. Even if you'd use a real regex, it would eat the last character:
> "xyz\\,xyz,xyz".split(/[^\\],/, 2)
["xyz\\,xy", "xyz"]
If you don't want the z to be eaten, I'd suggest:
var str = "....";
return str.split(",").reduce(function(res, part) {
var l = res.length;
if (l && res[l-1].substr(-1) == "\\" || l<2)
// ^ ^^ ^
// not the first was escaped limit
res[l-1] += ","+part;
else
res.push(part);
return;
}, []);
Reading between the lines, it looks like you want to split a string by , characters that are not preceded by \ characters.
It would be really great if JavaScript had a regular expression lookbehind (and negative lookbehind) pattern, but unfortunately it does not. What it does have is a lookahead ((?=) )and negative lookahead ((?!)) pattern. Make sure to review the documentation.
You can use these as a lookbehind if you reverse the string:
var str,
reverseStr,
arr,
reverseArr;
//don't forget to escape your backslashes
str = '\\,str\\,i,ing';
//reverse your string
reverseStr = str.split('').reverse().join('');
//split the array on `,`s that aren't followed by `\`
reverseArr = reverseStr.split(/,(?!\\)/);
//reverse the reversed array, and reverse each string in the array
arr = reverseArr.reverse().map(function (val) {
return val.split('').reverse().join('');
});
You picked a tough character to match- a forward slash preceding a comma is apt to disappear while you pass it around in a string, since '\,'==','...
var s= 'My dog, the one with two \\, blue \\,eyes, is asleep.';
var a= [], M, rx=/(\\?),/g;
while((M= rx.exec(s))!= null){
if(M[1]) continue;
a.push(s.substring(0, rx.lastIndex-1));
s= s.substring(rx.lastIndex);
rx.lastIndex= 0;
};
a.push(s);
/* returned value: (Array)
My dog
the one with two \, blue \,eyes
is asleep.
*/
Find something which will not be present in your original string, say "###". Replace "\\," with it. Split the resulting string by ",". Replace "###" back with "\\,".
Something like this:
<script type="text/javascript">
var s1 = "\\,str\\,i,ing";
var s2 = s1.replace(/\\,/g,"###");
console.log(s2);
var s3 = s2.split(",");
for (var i=0;i<s3.length;i++)
{
s3[i] = s3[i].replace(/###/g,"\\,");
}
console.log(s3);
</script>
See JSFiddle

Categories