I have the following string variable:
var sTest = "OOR|the OOR me|this is test|OOR|OOR this is me";
How can I use the match function to search out total of count for word "OOR|"?
When I use the following code, it will return me 4 as the result
var count = (sTest.match(/OOR/g) || []).length;
and it will throw error when I using the following code:
var count = (sTest.match(/OOR|/g) || []).length;
Does anyone know how could I solve this issue?
I expected the return result is 2.
The | has meaning for regular expressions, so if you want to match it as a string you have to escape it like this:
(sTest.match(/OOR\|/g) || []).length;
Then you will get the desired result.
As an aside, | is just "or". Meaning /abc|xyz/g will match "abc" and "xyz"
Related
I have a situation where I have to split a string by checking a condition whether a string begins with any of this character "<= | >= | = | !="
=>value desired result [=>,value]
>=value desired result [>=,value]
somevalue desired result [somevalue]
My attempt
var string1 = '<=value';
var splitString = string1.split(/\s+(?:<=|>=|=|!=)\s+/);
console.log(splitString);
To get the outputs you require
note: the .map at the end is to remove the blank entry in the case of somevalue
input.match(/(<=|>=|=|!=)?\s*(.+)/).slice(1)).map(x => x.slice(x[0] === undefined ? 1 : 0)
The snippet below tests all three of your inputs, (plus the other two you never mentioned in the examples) - which is why it's wrapped in inputs.map(input => ....)
const inputs = ['<=value', '>=value', '!= value', '=value', 'somevalue'];
const outputs = inputs.map(input => input.match(/(>=|<=|=|\!=)?\s*(.+)/).slice(1)).map(x => x.slice(x[0] === undefined ? 1 : 0));
console.log(outputs);
note: your question asks for <=, >=, != or =
and your attempted regex is <=, >=, != or =
and then your examples have =>, >= only?
your regex doesn't even look for =>!
So, I've amended the example "inputs" to be sane ... i.e. using what the question and attempted regex ask for - I think your input examples were hastily put together :p
There can possibly be multiple correct answers, but I think the shortest is this
[<>!](?:=)|=
You can test or try modifications here: https://regex101.com/r/kXIOvx/1 . This is a good site for regex newbies or even veterans when they don't want to run the whole program just to verify a regex line (which you have to do everytime you write a regex line)
Groups () are included in the split result, and filter can be used to remove empty entries:
var re = /([<>!]?=)/g
console.log( '<=value'.split(re).filter(Boolean) )
console.log( '=value'.split(re).filter(Boolean) )
console.log( 'value'.split(re) )
Or match instead of splitting:
var re = /[<>!]?=|.+/g
console.log( '<=value'.match(re) )
console.log( '=value'.match(re) )
console.log( 'value'.match(re) )
After coming to the shocking realization that regular expressions in JavaScript are somewhat different from the ones in PCE, I am stuck with the following.
In php I extract a number after x:
(?x)[0-9]+
In JavaScript the same regex doesn't work, due to invalid group resulting from the capturing parenthesis difference.
So I am trying to achieve the same trivial functionality, but I keep getting both the x and the number:
(?:x)([0-9]+)
How do I capture the number after x without including x?
This works too:
/(?:x)([0-9]+)/.test('YOUR_STRING');
Then, the value you want is:
RegExp.$1 // group 1
You can try the following regex: (?!x)[0-9]+
fiddle here: https://jsfiddle.net/xy6x938e/1/
This is assuming that you are now looking for an x followed by a number, it uses a capture group to capture just the numbers section.
var myString = "x12345";
var myRegexp = /x([0-9]+)/g;
var match = myRegexp.exec(myString);
var myString2 = "z12345";
var match2 = myRegexp.exec(myString2);
if(match != null && match.length > 1){
alert('match1:' + match[1]);
}
else{
alert('no match 1');
}
if(match2 != null && match2.length > 1){
alert('match2:' + match2[1]);
}
else{
alert('no match 2');
}
(\d+) try this!
i have tested on this tool with x12345
http://www.regular-expressions.info/javascriptexample.html
How do I capture the number after x without including x?
In fact, you just want to extract a sequence of digits after a fixed string/known pattern.
Your PCRE (PHP) regex, (?x)[0-9]+, is wrong becaue (?x) is an inline version of a PCRE_EXTENDED VERBOSE/COMMENTS flag (see "Pattern Modifiers"). It does not do anything meaningful in this case, (?x)[0-9]+ is equal to [0-9]+ or \d+.
You can use
console.log("x15 x25".match(/(?<=x)\d+/g));
You can also use a capturing group and then extract Group 1 value after a match is obtained:
const match = /x(\d+)/.exec("x15");
if (match) {
console.log(match[1]); // Getting the first match
}
// All matches
const matches = Array.from("x15,x25".matchAll(/x(\d+)/g), x=>x[1]);
console.log(matches);
You still can use exclusive pattern (?!...)
So, for your example it will be /(?!x)[0-9]+/. Give a try to the following:
/(?!x)\d+/.exec('x123')
// => ["123"]
I have a variable which contain a string and I want to return only the letters from regular expression (“b” and “D”) or any letter that I indicate on regular expression from match().
var kk = "AaBbCcDd".match(/b|D/g);
kk.forEach(function(value,index){
console.log(value,index)
});
My problem is that regular expression I think because is returning b and D but the index is not the index from kk variable and I'm not really sure, why ... so if someone can help me a little bit because I stuck
The match method from javascript only returns an array with the given match:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match
You would need to implement a new function which will loop through all characters of your string and return the given index of the matches.
This method could use the function search from String.prototype: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/search
You have to write a new function to get the index of the matched regex like a sample below:-
var re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
alert("match found at " + match.index);
}
Hope this will help you
Actually this is the answer :
var kk = "AaBbCcDd".match(/B?d?/g);
kk.forEach(function(value,index){
console.log(value,index)
});
if someone will encounter this scenario ...
The match() regular expresion B?d? will return an array indicating the position of "B" and "d" of the initial array kk.
After coming to the shocking realization that regular expressions in JavaScript are somewhat different from the ones in PCE, I am stuck with the following.
In php I extract a number after x:
(?x)[0-9]+
In JavaScript the same regex doesn't work, due to invalid group resulting from the capturing parenthesis difference.
So I am trying to achieve the same trivial functionality, but I keep getting both the x and the number:
(?:x)([0-9]+)
How do I capture the number after x without including x?
This works too:
/(?:x)([0-9]+)/.test('YOUR_STRING');
Then, the value you want is:
RegExp.$1 // group 1
You can try the following regex: (?!x)[0-9]+
fiddle here: https://jsfiddle.net/xy6x938e/1/
This is assuming that you are now looking for an x followed by a number, it uses a capture group to capture just the numbers section.
var myString = "x12345";
var myRegexp = /x([0-9]+)/g;
var match = myRegexp.exec(myString);
var myString2 = "z12345";
var match2 = myRegexp.exec(myString2);
if(match != null && match.length > 1){
alert('match1:' + match[1]);
}
else{
alert('no match 1');
}
if(match2 != null && match2.length > 1){
alert('match2:' + match2[1]);
}
else{
alert('no match 2');
}
(\d+) try this!
i have tested on this tool with x12345
http://www.regular-expressions.info/javascriptexample.html
How do I capture the number after x without including x?
In fact, you just want to extract a sequence of digits after a fixed string/known pattern.
Your PCRE (PHP) regex, (?x)[0-9]+, is wrong becaue (?x) is an inline version of a PCRE_EXTENDED VERBOSE/COMMENTS flag (see "Pattern Modifiers"). It does not do anything meaningful in this case, (?x)[0-9]+ is equal to [0-9]+ or \d+.
You can use
console.log("x15 x25".match(/(?<=x)\d+/g));
You can also use a capturing group and then extract Group 1 value after a match is obtained:
const match = /x(\d+)/.exec("x15");
if (match) {
console.log(match[1]); // Getting the first match
}
// All matches
const matches = Array.from("x15,x25".matchAll(/x(\d+)/g), x=>x[1]);
console.log(matches);
You still can use exclusive pattern (?!...)
So, for your example it will be /(?!x)[0-9]+/. Give a try to the following:
/(?!x)\d+/.exec('x123')
// => ["123"]
I have a string that I expect to be formatted like so:
{List:[Names:a,b,c][Ages:1,2,3]}
My query looks like this in javascript:
var str = "{List:[Names:a,b,c][Ages:1,2,3]}";
var result = str.match(/^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g);
Note: I recognize that with this regex it would pass with something like "Ages:,,,", but I'm not worried about that at the moment.
I was expecting to get this back:
result[0] = "{List:[Names:a,b,c][Ages:1,2,3]}"
result[1] = "a,b,c"
result[2] = "1,2,3"
But no matter what I seem to do to the regular expression, it refuses to return an array of more than one match, I just get the full string back (because it passes, which is a start):
result = ["{List:[Names:a,b,c][Ages:1,2,3]}"]
I've looked through a bunch of questions on here already, as well as other 'intro' articles, and none of them seem to address something this basic. I'm sure it's something foolish that I've overlooked, but I truly have no idea what it is :(
So this is a difference in how the global flag is applied in Regular Expressions in JavaScript.
In .match, the global flag (/g at the end) will return an array of every incident where the regular expression matches the string. Without that flag, .match will return an array of all of the groupings in the string.
eg:
var str = "{List:[Names:a,b,c][Ages:1,2,3]}";
str += str;
// removed ^ and $ for demonstration purposes
var results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/g)
console.log(results)
// ["{List:[Names:a,b,c][Ages:1,2,3]}", "{List:[Names:a,b,c][Ages:1,2,3]}"]
str = "{List:[Names:a,b,c][Ages:1,2,3]}{List:[Names:a,b,c][Ages:3,4,5]}";
results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/g);
console.log(results)
//["{List:[Names:a,b,c][Ages:1,2,3]}", "{List:[Names:a,b,c][Ages:3,4,5]}"]
Now, if we remove that /g flag:
// leaving str as above
results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/);
console.log(results)
//["{List:[Names:a,b,c][Ages:1,2,3]}", "a,b,c", "1,2,3"]
And as a note as to why regex.exec worked, that is because:
If the regular expression does not include the g flag, returns the same result as regexp.exec(string).
You're looking for the form needle.exec(haystack)
From my console:
> haystack = "{List:[Names:a,b,c][Ages:1,2,3]}";
"{List:[Names:a,b,c][Ages:1,2,3]}"
> needle = /^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g ;
/^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g
> needle.exec(haystack);
["{List:[Names:a,b,c][Ages:1,2,3]}", "a,b,c", "1,2,3"]