I have put this together getting help from other SO answers. With this I get ["__COL__", "COL"], what I want to get is ["COL", "COL_ID"]. What is the proper regex to use?
var myString = "this is a __COL__ and here is a __COL_ID__";
var myRegexp = /__([A-Z]+)__/g;
var match = myRegexp.exec(myString);
console.log(match); // ["__COL__", "COL"]
You are just including only uppercase alphabets, and missing the _. So, the RegEx becomes like this /__(\[A-Z_\]+)__/g. And exec function returns only the first match, so, we have to exec again and again till it returns null.
exec returns,
If the match succeeds, the exec method returns an array and updates
properties of the regular expression object. The returned array has
the matched text as the first item, and then one item for each
capturing parenthesis that matched containing the text that was
captured.
In our case, the first value would be the entire matched string, the second value would be the captured string. So, we are pushing only match[1] in the result.
var myString = "this is a __COL__ and here is a __COL_ID__";
var myRegexp = /__([A-Z_]+)__/g, match = myRegexp.exec(myString), result = [];
while (match) {
result.push(match[1]);
match = myRegexp.exec(myString);
}
console.log(result);
Output
[ 'COL', 'COL_ID' ]
This works (here's the jsfiddle):
var myString = "this is a __COL__ and here is a __COL_ID__";
var myRegexp = /([A-Z]+_[A-Z]+|[A-Z]+)(?=__)/g;
var match = myString.match(myRegexp);
console.log(match);
Related
So I have the following url:
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
I want to take username and token out of it;
I tried:
var match = (/#\{(.*?)\}/g.exec(oURL));
console.log(match);
but it is giving me:
["#{username}", "username", index: 27, input: "https://graph.facebook.com/#{username}/posts?access_token=#{token}"
Why isn't catching token?
Thanks
The problem is that exec only returns the first match from the given index whenever called.
Returns
If the match succeeds, the exec() method returns an array and updates
properties of the regular expression object. The returned array has
the matched text as the first item, and then one item for each
capturing parenthesis that matched containing the text that was
captured.
If the match fails, the exec() method returns null.
You would need to loop, continuously matching again to find all the matches.
var matches = [],
match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
matches.push(match)
}
console.log(matches)
However, if you are only interested in the first capture group, you can only add those to the matches array:
var matches = [],
match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
matches.push(match[1])
}
console.log(matches)
Try this instead:
oURL.match(/#\{(.*?)\}/g)
The answer you accepted is perfect, but I thought I'd also add that it's pretty easy to create a little helper function like this:
function getMatches(str, expr) {
var matches = [];
var match;
while (match = expr.exec(str)) {
matches.push(match[1]);
}
return matches;
}
Then you can use it a little more intuitively.
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
var expr = /#\{([^\{]*)?\}/g;
var result = getMatches(oURL, expr);
console.log(result);
http://codepen.io/Chevex/pen/VLyaeG
Try this:
var match = (/#\{(.*?)\}.*?#\{(.*?)\}/g.exec(oURL));
How is it possible to match more than one string with regular expressions?
Here I want to match both name and txt, but only name is matched?
var reg = new RegExp('%([a-z]+)%', "g");
reg.exec('%name% some text %txt%');
You need to use String.match instead of exec:
'%name% some text %txt%'.match(reg);
Use match instead:
'%name% %txt%'.match(reg); //["%name%", "%txt%"]
exec only retrieves the first match (albeit with capturing groups).
If the capturing groups are important to you, you can use a loop:
var matches = [];
var str = '%name% some text %txt%';
var reg = new RegExp('%([a-z]+)%', "g");
while (match = reg.exec(str)){
matches.push(match);
}
If you only want to keep the captured groups, use this instead:
matches.push(match[1]);
The g flag does work but needs to be executed on the same string multiple times
var reg = new RegExp('%([a-z]+)%', "g");
var str = '%name% some text %txt%';
var result;
while( result = reg.exec( str ) ) { // returns array of current match
console.log( result[1] ); // index 0 is matched expression. Thereafter matched groups.
}
The above outputs name & txt to the console.
Example here
I have a string where I'm trying to grab the integer inside. The string looks like:
"(2) This is a string"
I need to grap that 2. but it could be any number so I tried:
var str = "(2) this is a string";
var patt = /\(\d\)/;
var num = str.match(patt);
This doesn't return the correct answer. Should I do a split on the () or is there a better regexp?
var str = "(2) this is a string";
var patt = /\((\d)\)/;
var num = str.match(patt)[1];
2 things. When you want to capture a segment form a matched string, you use () to note that. So I just wrapped the \d in parens to capture it.
Second, in order to access the captured segments, you must drill into the returned array. the match method will return an array where the first item is the entire matched string, and the second item is any matched capture groups. So use [1] to fetch the first capture group (second item in array)
Use this. doesnt matter how many parenthesis
var str = "(2) this is a string";
var patt = /\(\d\)/;
var num = str.match(patt)[0].replace("(", "").replace(")","")
This should work
var str = "(2) this is a string";
var a = /\([\d]*\)/g.exec(str)[0];
var num = a.substring(1, a.length-1);
var str = "(2) this is a string";
var patt = /\((\d+)\)/;
alert(str.match(patt)[1]);
This works!
Why it works. Because inside the (()) mayhem there's also a capture which populates the [1] elements in the matches array.
I have a strings "add_dinner", "add_meeting", "add_fuel_surcharge" and I want to get characters that are preceded by "add_" (dinner, meeting, fuel_surcharge).
[^a][^d]{2}[^_]\w+
I have tried this one, but it only works for "add_dinner"
[^add_]\w+
This one works for "add_fuel_surcharge", but takes "inner" from "add_dinner"
Help me to understand please.
Use capturing groups:
/^add_(\w+)$/
Check the returned array to see the result.
Since JavaScript doesn't support lookbehind assertions, you need to use a capturing group:
var myregexp = /add_(\w+)/;
var match = myregexp.exec(subject);
if (match != null) {
result = match[1];
}
[^add_] is a character class that matches a single character except a, d or _. When applied to add_dinner, the first character it matches is i, and \w+ then matches nner.
The [^...] construct matches any single character except the ones listed. So [^add_] matches any single character other than "a", "d" or "_".
If you want to retrieve the bit after the _ you can do this:
/add_(\w+_)/
Where the parentheses "capture" the part of the expression inside. So to get the actual text from a string:
var s = "add_meeting";
var result = s.match(/add_(\w+)/)[1];
This assumes the string will match such that you can directly get the second element in the returned array that will be the "meeting" part that matched (\w+).
If there's a possibility that you'll be testing a string that won't match you need to test that the result of match() is not null.
(Or, possibly easier to understand: result = "add_meeting".split("_")[1];)
You can filter _ string by JavaScript for loop ,
var str = ['add_dinner', 'add_meeting', 'add_fuel_surcharge'];
var filterString = [];
for(var i = 0; i < str.length; i ++){
if(str[i].indexOf("_")>-1){
filterString.push(str[i].substring(str[i].indexOf("_") + 1, str[i].length));
}
}
alert(filterString.join(", "));
I have the following string: pass[1][2011-08-21][total_passes]
How would I extract the items between the square brackets into an array? I tried
match(/\[(.*?)\]/);
var s = 'pass[1][2011-08-21][total_passes]';
var result = s.match(/\[(.*?)\]/);
console.log(result);
but this only returns [1].
Not sure how to do this.. Thanks in advance.
You are almost there, you just need a global match (note the /g flag):
match(/\[(.*?)\]/g);
Example: http://jsfiddle.net/kobi/Rbdj4/
If you want something that only captures the group (from MDN):
var s = "pass[1][2011-08-21][total_passes]";
var matches = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((match = pattern.exec(s)) != null)
{
matches.push(match[1]);
}
Example: http://jsfiddle.net/kobi/6a7XN/
Another option (which I usually prefer), is abusing the replace callback:
var matches = [];
s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);})
Example: http://jsfiddle.net/kobi/6CEzP/
var s = 'pass[1][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r ; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
example proving the edge case of unbalanced [];
var s = 'pass[1]]][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
add the global flag to your regex , and iterate the array returned .
match(/\[(.*?)\]/g)
I'm not sure if you can get this directly into an array. But the following code should work to find all occurences and then process them:
var string = "pass[1][2011-08-21][total_passes]";
var regex = /\[([^\]]*)\]/g;
while (match = regex.exec(string)) {
alert(match[1]);
}
Please note: i really think you need the character class [^\]] here. Otherwise in my test the expression would match the hole string because ] is also matches by .*.
'pass[1][2011-08-21][total_passes]'.match(/\[.+?\]/g); // ["[1]","[2011-08-21]","[total_passes]"]
Explanation
\[ # match the opening [
Note: \ before [ tells that do NOT consider as a grouping symbol.
.+? # Accept one or more character but NOT greedy
\] # match the closing ] and again do NOT consider as a grouping symbol
/g # do NOT stop after the first match. Do it for the whole input string.
You can play with other combinations of the regular expression
https://regex101.com/r/IYDkNi/1
[C#]
string str1 = " pass[1][2011-08-21][total_passes]";
string matching = #"\[(.*?)\]";
Regex reg = new Regex(matching);
MatchCollection matches = reg.Matches(str1);
you can use foreach for matched strings.