How do you access the matched groups in a JavaScript regular expression?
I want to match a portion of a string using a regular expression and then access that parenthesized substring:
var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.
The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.
javascript regex
add a comment |
I want to match a portion of a string using a regular expression and then access that parenthesized substring:
var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.
The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.
javascript regex
add a comment |
I want to match a portion of a string using a regular expression and then access that parenthesized substring:
var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.
The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.
javascript regex
I want to match a portion of a string using a regular expression and then access that parenthesized substring:
var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.
The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.
javascript regex
javascript regex
edited May 23 '17 at 11:55
Community♦
11
11
asked Jan 11 '09 at 7:21
nickf
369k171581687
369k171581687
add a comment |
add a comment |
13 Answers
13
active
oldest
votes
You can access capturing groups like this:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abcAnd if there are multiple matches you can iterate over them:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}
94
+1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
– ianaz
Aug 28 '12 at 12:06
5
@ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
– spinningarrow
Oct 16 '12 at 7:26
11
Why do the above instead of:var match = myString.match(myRegexp); // alert(match[1])?
– JohnAllen
Dec 30 '13 at 17:39
21
No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
– George Chen
Jun 6 '14 at 18:33
2
Another way not to run into infinite loop is to explicetly update string, e.g.string = string.substring(match.index + match[0].length)
– Olga
Feb 11 '16 at 11:28
|
show 6 more comments
Here’s a method you can use to get the nth capturing group for each match:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);
7
This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
– Rob Evans
May 11 '13 at 12:08
11
mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
– Druska
Sep 4 '13 at 18:45
2
I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
– ravishi
Nov 21 '13 at 20:00
4
@MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
– wallacer
Oct 29 '14 at 18:34
3
@MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
– wallacer
Nov 12 '14 at 23:44
|
show 7 more comments
var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.
1
It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
– B.F.
Apr 22 '15 at 21:09
@B.F.Honestly, I added "doesn't work onformat_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to captureaonly", ie. the first alphabetical part afterformat_.
– PhiLho
Apr 23 '15 at 7:41
I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
– B.F.
Apr 23 '15 at 10:43
add a comment |
In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:
var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);
After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):
var yourstring = 'something format_abc something format_def something format_ghi';
var matches = ;
yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );
After this, I don't think I'm ever going to use .match() for hardly anything ever again.
add a comment |
Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.
(FF2 went as far as typeof(/pattern/) == 'function')
It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.
Instead, use either method previously mentioned by others: RegExp#exec or String#match.
They offer the same results:
var regex = /(?:^|s)format_(.*?)(?:s|$)/;
var input = "something format_abc";
regex(input); //=> [" format_abc", "abc"]
regex.exec(input); //=> [" format_abc", "abc"]
input.match(regex); //=> [" format_abc", "abc"]
add a comment |
Last but not least, I found one line of code that worked fine for me (JS ES6):
let reg = /#([S]+)/igm; // Get hashtags.
let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';
let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
console.log(matches);This will return:
['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']
1
this is works well except when match can't find anything then map doesn't work.
– MBehtemam
Nov 25 '17 at 11:23
add a comment |
Terminology used in this answer:
Match indicates the result of running your RegEx pattern against your string like so:someString.match(regexPattern).
Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.
Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so:/format_(.*?)/g, where(.*?)would be a matched group.) These reside within matched patterns.
Description
To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.
Code examples
Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.
Concise versions (less code, more syntactic sugar)
These are less performant since they basically implement a forEach-loop instead of the faster for-loop.
// Concise ES6/ES2015 syntax
const searchString =
(string, pattern) =>
string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
// Or if you will, with ES5 syntax
function searchString(string, pattern) {
return string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
Performant versions (more code, less syntactic sugar)
// Performant ES6/ES2015 syntax
const searchString = (string, pattern) => {
let result = ;
const matches = string.match(new RegExp(pattern.source, pattern.flags));
for (let i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
};
// Same thing, but with ES5 syntax
function searchString(string, pattern) {
var result = ;
var matches = string.match(new RegExp(pattern.source, pattern.flags));
for (var i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.
add a comment |
There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.
var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...
Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!
1
This works and feels more natural.
– Vidar
May 29 at 11:54
1
Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
– Shadymilkman01
Sep 13 at 22:00
add a comment |
A one liner that is practical only if you have a single pair of parenthesis:
while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};
3
Why notwhile (match = myRegex.exec(myStr)) matches.push(match[1])
– willlma
Apr 6 '17 at 18:44
@willlma Yep!..
– Nabil Kadimi
May 23 '17 at 20:00
add a comment |
Using your code:
console.log(arr[1]); // prints: abc
console.log(arr[0]); // prints: format_abc
Edit: Safari 3, if it matters.
add a comment |
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
var myRegEx = /clear bal.+?(d+.?d{2})/gi;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);add a comment |
Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:
/bformat_(.*?)b/
(But, of course, I'm not sure because I don't know the context of the regex.)
it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
– nickf
Jan 11 '09 at 12:04
Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
– PEZ
Jan 11 '09 at 12:21
add a comment |
/*Regex function for extracting object from "window.location.search" string.
*/
var search = "?a=3&b=4&c=7"; // Example search string
var getSearchObj = function (searchString) {
var match, key, value, obj = {};
var pattern = /(w+)=(w+)/g;
var search = searchString.substr(1); // Remove '?'
while (match = pattern.exec(search)) {
obj[match[0].split('=')[0]] = match[0].split('=')[1];
}
return obj;
};
console.log(getSearchObj(search));
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f432493%2fhow-do-you-access-the-matched-groups-in-a-javascript-regular-expression%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
13 Answers
13
active
oldest
votes
13 Answers
13
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can access capturing groups like this:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abcAnd if there are multiple matches you can iterate over them:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}
94
+1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
– ianaz
Aug 28 '12 at 12:06
5
@ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
– spinningarrow
Oct 16 '12 at 7:26
11
Why do the above instead of:var match = myString.match(myRegexp); // alert(match[1])?
– JohnAllen
Dec 30 '13 at 17:39
21
No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
– George Chen
Jun 6 '14 at 18:33
2
Another way not to run into infinite loop is to explicetly update string, e.g.string = string.substring(match.index + match[0].length)
– Olga
Feb 11 '16 at 11:28
|
show 6 more comments
You can access capturing groups like this:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abcAnd if there are multiple matches you can iterate over them:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}
94
+1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
– ianaz
Aug 28 '12 at 12:06
5
@ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
– spinningarrow
Oct 16 '12 at 7:26
11
Why do the above instead of:var match = myString.match(myRegexp); // alert(match[1])?
– JohnAllen
Dec 30 '13 at 17:39
21
No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
– George Chen
Jun 6 '14 at 18:33
2
Another way not to run into infinite loop is to explicetly update string, e.g.string = string.substring(match.index + match[0].length)
– Olga
Feb 11 '16 at 11:28
|
show 6 more comments
You can access capturing groups like this:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abcAnd if there are multiple matches you can iterate over them:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}You can access capturing groups like this:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abcAnd if there are multiple matches you can iterate over them:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abcvar myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abcvar myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}edited Aug 16 '16 at 1:42
Ruslan López
2,80811326
2,80811326
answered Jan 11 '09 at 7:26
CMS
586k162841809
586k162841809
94
+1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
– ianaz
Aug 28 '12 at 12:06
5
@ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
– spinningarrow
Oct 16 '12 at 7:26
11
Why do the above instead of:var match = myString.match(myRegexp); // alert(match[1])?
– JohnAllen
Dec 30 '13 at 17:39
21
No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
– George Chen
Jun 6 '14 at 18:33
2
Another way not to run into infinite loop is to explicetly update string, e.g.string = string.substring(match.index + match[0].length)
– Olga
Feb 11 '16 at 11:28
|
show 6 more comments
94
+1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
– ianaz
Aug 28 '12 at 12:06
5
@ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
– spinningarrow
Oct 16 '12 at 7:26
11
Why do the above instead of:var match = myString.match(myRegexp); // alert(match[1])?
– JohnAllen
Dec 30 '13 at 17:39
21
No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
– George Chen
Jun 6 '14 at 18:33
2
Another way not to run into infinite loop is to explicetly update string, e.g.string = string.substring(match.index + match[0].length)
– Olga
Feb 11 '16 at 11:28
94
94
+1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
– ianaz
Aug 28 '12 at 12:06
+1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
– ianaz
Aug 28 '12 at 12:06
5
5
@ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
– spinningarrow
Oct 16 '12 at 7:26
@ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
– spinningarrow
Oct 16 '12 at 7:26
11
11
Why do the above instead of:
var match = myString.match(myRegexp); // alert(match[1])?– JohnAllen
Dec 30 '13 at 17:39
Why do the above instead of:
var match = myString.match(myRegexp); // alert(match[1])?– JohnAllen
Dec 30 '13 at 17:39
21
21
No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
– George Chen
Jun 6 '14 at 18:33
No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
– George Chen
Jun 6 '14 at 18:33
2
2
Another way not to run into infinite loop is to explicetly update string, e.g.
string = string.substring(match.index + match[0].length)– Olga
Feb 11 '16 at 11:28
Another way not to run into infinite loop is to explicetly update string, e.g.
string = string.substring(match.index + match[0].length)– Olga
Feb 11 '16 at 11:28
|
show 6 more comments
Here’s a method you can use to get the nth capturing group for each match:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);
7
This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
– Rob Evans
May 11 '13 at 12:08
11
mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
– Druska
Sep 4 '13 at 18:45
2
I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
– ravishi
Nov 21 '13 at 20:00
4
@MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
– wallacer
Oct 29 '14 at 18:34
3
@MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
– wallacer
Nov 12 '14 at 23:44
|
show 7 more comments
Here’s a method you can use to get the nth capturing group for each match:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);
7
This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
– Rob Evans
May 11 '13 at 12:08
11
mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
– Druska
Sep 4 '13 at 18:45
2
I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
– ravishi
Nov 21 '13 at 20:00
4
@MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
– wallacer
Oct 29 '14 at 18:34
3
@MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
– wallacer
Nov 12 '14 at 23:44
|
show 7 more comments
Here’s a method you can use to get the nth capturing group for each match:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);Here’s a method you can use to get the nth capturing group for each match:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);edited Apr 17 '15 at 6:52
Blowsie
34k1375102
34k1375102
answered Jan 8 '13 at 8:26
Mathias Bynens
103k39174222
103k39174222
7
This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
– Rob Evans
May 11 '13 at 12:08
11
mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
– Druska
Sep 4 '13 at 18:45
2
I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
– ravishi
Nov 21 '13 at 20:00
4
@MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
– wallacer
Oct 29 '14 at 18:34
3
@MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
– wallacer
Nov 12 '14 at 23:44
|
show 7 more comments
7
This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
– Rob Evans
May 11 '13 at 12:08
11
mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
– Druska
Sep 4 '13 at 18:45
2
I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
– ravishi
Nov 21 '13 at 20:00
4
@MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
– wallacer
Oct 29 '14 at 18:34
3
@MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
– wallacer
Nov 12 '14 at 23:44
7
7
This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
– Rob Evans
May 11 '13 at 12:08
This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
– Rob Evans
May 11 '13 at 12:08
11
11
mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
– Druska
Sep 4 '13 at 18:45
mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
– Druska
Sep 4 '13 at 18:45
2
2
I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
– ravishi
Nov 21 '13 at 20:00
I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
– ravishi
Nov 21 '13 at 20:00
4
4
@MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
– wallacer
Oct 29 '14 at 18:34
@MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
– wallacer
Oct 29 '14 at 18:34
3
3
@MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
– wallacer
Nov 12 '14 at 23:44
@MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
– wallacer
Nov 12 '14 at 23:44
|
show 7 more comments
var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.
1
It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
– B.F.
Apr 22 '15 at 21:09
@B.F.Honestly, I added "doesn't work onformat_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to captureaonly", ie. the first alphabetical part afterformat_.
– PhiLho
Apr 23 '15 at 7:41
I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
– B.F.
Apr 23 '15 at 10:43
add a comment |
var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.
1
It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
– B.F.
Apr 22 '15 at 21:09
@B.F.Honestly, I added "doesn't work onformat_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to captureaonly", ie. the first alphabetical part afterformat_.
– PhiLho
Apr 23 '15 at 7:41
I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
– B.F.
Apr 23 '15 at 10:43
add a comment |
var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.
var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.
var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);edited May 23 '17 at 16:08
Michael
3,41333756
3,41333756
answered Jan 11 '09 at 9:10
PhiLho
34.7k378121
34.7k378121
1
It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
– B.F.
Apr 22 '15 at 21:09
@B.F.Honestly, I added "doesn't work onformat_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to captureaonly", ie. the first alphabetical part afterformat_.
– PhiLho
Apr 23 '15 at 7:41
I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
– B.F.
Apr 23 '15 at 10:43
add a comment |
1
It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
– B.F.
Apr 22 '15 at 21:09
@B.F.Honestly, I added "doesn't work onformat_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to captureaonly", ie. the first alphabetical part afterformat_.
– PhiLho
Apr 23 '15 at 7:41
I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
– B.F.
Apr 23 '15 at 10:43
1
1
It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
– B.F.
Apr 22 '15 at 21:09
It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
– B.F.
Apr 22 '15 at 21:09
@B.F.Honestly, I added "doesn't work on
format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.– PhiLho
Apr 23 '15 at 7:41
@B.F.Honestly, I added "doesn't work on
format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.– PhiLho
Apr 23 '15 at 7:41
I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
– B.F.
Apr 23 '15 at 10:43
I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
– B.F.
Apr 23 '15 at 10:43
add a comment |
In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:
var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);
After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):
var yourstring = 'something format_abc something format_def something format_ghi';
var matches = ;
yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );
After this, I don't think I'm ever going to use .match() for hardly anything ever again.
add a comment |
In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:
var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);
After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):
var yourstring = 'something format_abc something format_def something format_ghi';
var matches = ;
yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );
After this, I don't think I'm ever going to use .match() for hardly anything ever again.
add a comment |
In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:
var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);
After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):
var yourstring = 'something format_abc something format_def something format_ghi';
var matches = ;
yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );
After this, I don't think I'm ever going to use .match() for hardly anything ever again.
In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:
var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);
After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):
var yourstring = 'something format_abc something format_def something format_ghi';
var matches = ;
yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );
After this, I don't think I'm ever going to use .match() for hardly anything ever again.
answered Jul 17 '14 at 4:53
Alexz
23123
23123
add a comment |
add a comment |
Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.
(FF2 went as far as typeof(/pattern/) == 'function')
It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.
Instead, use either method previously mentioned by others: RegExp#exec or String#match.
They offer the same results:
var regex = /(?:^|s)format_(.*?)(?:s|$)/;
var input = "something format_abc";
regex(input); //=> [" format_abc", "abc"]
regex.exec(input); //=> [" format_abc", "abc"]
input.match(regex); //=> [" format_abc", "abc"]
add a comment |
Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.
(FF2 went as far as typeof(/pattern/) == 'function')
It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.
Instead, use either method previously mentioned by others: RegExp#exec or String#match.
They offer the same results:
var regex = /(?:^|s)format_(.*?)(?:s|$)/;
var input = "something format_abc";
regex(input); //=> [" format_abc", "abc"]
regex.exec(input); //=> [" format_abc", "abc"]
input.match(regex); //=> [" format_abc", "abc"]
add a comment |
Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.
(FF2 went as far as typeof(/pattern/) == 'function')
It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.
Instead, use either method previously mentioned by others: RegExp#exec or String#match.
They offer the same results:
var regex = /(?:^|s)format_(.*?)(?:s|$)/;
var input = "something format_abc";
regex(input); //=> [" format_abc", "abc"]
regex.exec(input); //=> [" format_abc", "abc"]
input.match(regex); //=> [" format_abc", "abc"]
Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.
(FF2 went as far as typeof(/pattern/) == 'function')
It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.
Instead, use either method previously mentioned by others: RegExp#exec or String#match.
They offer the same results:
var regex = /(?:^|s)format_(.*?)(?:s|$)/;
var input = "something format_abc";
regex(input); //=> [" format_abc", "abc"]
regex.exec(input); //=> [" format_abc", "abc"]
input.match(regex); //=> [" format_abc", "abc"]
answered Jan 11 '09 at 12:55
Jonathan Lonowski
92.3k25167181
92.3k25167181
add a comment |
add a comment |
Last but not least, I found one line of code that worked fine for me (JS ES6):
let reg = /#([S]+)/igm; // Get hashtags.
let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';
let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
console.log(matches);This will return:
['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']
1
this is works well except when match can't find anything then map doesn't work.
– MBehtemam
Nov 25 '17 at 11:23
add a comment |
Last but not least, I found one line of code that worked fine for me (JS ES6):
let reg = /#([S]+)/igm; // Get hashtags.
let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';
let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
console.log(matches);This will return:
['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']
1
this is works well except when match can't find anything then map doesn't work.
– MBehtemam
Nov 25 '17 at 11:23
add a comment |
Last but not least, I found one line of code that worked fine for me (JS ES6):
let reg = /#([S]+)/igm; // Get hashtags.
let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';
let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
console.log(matches);This will return:
['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']
Last but not least, I found one line of code that worked fine for me (JS ES6):
let reg = /#([S]+)/igm; // Get hashtags.
let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';
let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
console.log(matches);This will return:
['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']
let reg = /#([S]+)/igm; // Get hashtags.
let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';
let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
console.log(matches);let reg = /#([S]+)/igm; // Get hashtags.
let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';
let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
console.log(matches);edited Dec 21 at 14:54
answered Jan 3 '17 at 14:40
Sebastien H.
3,21021723
3,21021723
1
this is works well except when match can't find anything then map doesn't work.
– MBehtemam
Nov 25 '17 at 11:23
add a comment |
1
this is works well except when match can't find anything then map doesn't work.
– MBehtemam
Nov 25 '17 at 11:23
1
1
this is works well except when match can't find anything then map doesn't work.
– MBehtemam
Nov 25 '17 at 11:23
this is works well except when match can't find anything then map doesn't work.
– MBehtemam
Nov 25 '17 at 11:23
add a comment |
Terminology used in this answer:
Match indicates the result of running your RegEx pattern against your string like so:someString.match(regexPattern).
Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.
Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so:/format_(.*?)/g, where(.*?)would be a matched group.) These reside within matched patterns.
Description
To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.
Code examples
Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.
Concise versions (less code, more syntactic sugar)
These are less performant since they basically implement a forEach-loop instead of the faster for-loop.
// Concise ES6/ES2015 syntax
const searchString =
(string, pattern) =>
string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
// Or if you will, with ES5 syntax
function searchString(string, pattern) {
return string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
Performant versions (more code, less syntactic sugar)
// Performant ES6/ES2015 syntax
const searchString = (string, pattern) => {
let result = ;
const matches = string.match(new RegExp(pattern.source, pattern.flags));
for (let i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
};
// Same thing, but with ES5 syntax
function searchString(string, pattern) {
var result = ;
var matches = string.match(new RegExp(pattern.source, pattern.flags));
for (var i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.
add a comment |
Terminology used in this answer:
Match indicates the result of running your RegEx pattern against your string like so:someString.match(regexPattern).
Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.
Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so:/format_(.*?)/g, where(.*?)would be a matched group.) These reside within matched patterns.
Description
To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.
Code examples
Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.
Concise versions (less code, more syntactic sugar)
These are less performant since they basically implement a forEach-loop instead of the faster for-loop.
// Concise ES6/ES2015 syntax
const searchString =
(string, pattern) =>
string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
// Or if you will, with ES5 syntax
function searchString(string, pattern) {
return string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
Performant versions (more code, less syntactic sugar)
// Performant ES6/ES2015 syntax
const searchString = (string, pattern) => {
let result = ;
const matches = string.match(new RegExp(pattern.source, pattern.flags));
for (let i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
};
// Same thing, but with ES5 syntax
function searchString(string, pattern) {
var result = ;
var matches = string.match(new RegExp(pattern.source, pattern.flags));
for (var i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.
add a comment |
Terminology used in this answer:
Match indicates the result of running your RegEx pattern against your string like so:someString.match(regexPattern).
Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.
Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so:/format_(.*?)/g, where(.*?)would be a matched group.) These reside within matched patterns.
Description
To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.
Code examples
Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.
Concise versions (less code, more syntactic sugar)
These are less performant since they basically implement a forEach-loop instead of the faster for-loop.
// Concise ES6/ES2015 syntax
const searchString =
(string, pattern) =>
string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
// Or if you will, with ES5 syntax
function searchString(string, pattern) {
return string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
Performant versions (more code, less syntactic sugar)
// Performant ES6/ES2015 syntax
const searchString = (string, pattern) => {
let result = ;
const matches = string.match(new RegExp(pattern.source, pattern.flags));
for (let i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
};
// Same thing, but with ES5 syntax
function searchString(string, pattern) {
var result = ;
var matches = string.match(new RegExp(pattern.source, pattern.flags));
for (var i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.
Terminology used in this answer:
Match indicates the result of running your RegEx pattern against your string like so:someString.match(regexPattern).
Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.
Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so:/format_(.*?)/g, where(.*?)would be a matched group.) These reside within matched patterns.
Description
To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.
Code examples
Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.
Concise versions (less code, more syntactic sugar)
These are less performant since they basically implement a forEach-loop instead of the faster for-loop.
// Concise ES6/ES2015 syntax
const searchString =
(string, pattern) =>
string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
// Or if you will, with ES5 syntax
function searchString(string, pattern) {
return string
.match(new RegExp(pattern.source, pattern.flags))
.map(match =>
new RegExp(pattern.source, pattern.flags)
.exec(match));
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
Performant versions (more code, less syntactic sugar)
// Performant ES6/ES2015 syntax
const searchString = (string, pattern) => {
let result = ;
const matches = string.match(new RegExp(pattern.source, pattern.flags));
for (let i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
};
// Same thing, but with ES5 syntax
function searchString(string, pattern) {
var result = ;
var matches = string.match(new RegExp(pattern.source, pattern.flags));
for (var i = 0; i < matches.length; i++) {
result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
}
return result;
}
let string = "something format_abc",
pattern = /(?:^|s)format_(.*?)(?:s|$)/;
let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag
I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.
answered Aug 23 '17 at 22:36
Daniel Hallgren
337311
337311
add a comment |
add a comment |
There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.
var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...
Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!
1
This works and feels more natural.
– Vidar
May 29 at 11:54
1
Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
– Shadymilkman01
Sep 13 at 22:00
add a comment |
There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.
var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...
Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!
1
This works and feels more natural.
– Vidar
May 29 at 11:54
1
Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
– Shadymilkman01
Sep 13 at 22:00
add a comment |
There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.
var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...
Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!
There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.
var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...
Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!
edited Aug 11 '17 at 18:58
answered Jun 19 '17 at 19:47
Andre Carneiro
367213
367213
1
This works and feels more natural.
– Vidar
May 29 at 11:54
1
Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
– Shadymilkman01
Sep 13 at 22:00
add a comment |
1
This works and feels more natural.
– Vidar
May 29 at 11:54
1
Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
– Shadymilkman01
Sep 13 at 22:00
1
1
This works and feels more natural.
– Vidar
May 29 at 11:54
This works and feels more natural.
– Vidar
May 29 at 11:54
1
1
Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
– Shadymilkman01
Sep 13 at 22:00
Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
– Shadymilkman01
Sep 13 at 22:00
add a comment |
A one liner that is practical only if you have a single pair of parenthesis:
while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};
3
Why notwhile (match = myRegex.exec(myStr)) matches.push(match[1])
– willlma
Apr 6 '17 at 18:44
@willlma Yep!..
– Nabil Kadimi
May 23 '17 at 20:00
add a comment |
A one liner that is practical only if you have a single pair of parenthesis:
while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};
3
Why notwhile (match = myRegex.exec(myStr)) matches.push(match[1])
– willlma
Apr 6 '17 at 18:44
@willlma Yep!..
– Nabil Kadimi
May 23 '17 at 20:00
add a comment |
A one liner that is practical only if you have a single pair of parenthesis:
while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};
A one liner that is practical only if you have a single pair of parenthesis:
while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};
answered Jul 12 '14 at 15:41
Nabil Kadimi
7,32623147
7,32623147
3
Why notwhile (match = myRegex.exec(myStr)) matches.push(match[1])
– willlma
Apr 6 '17 at 18:44
@willlma Yep!..
– Nabil Kadimi
May 23 '17 at 20:00
add a comment |
3
Why notwhile (match = myRegex.exec(myStr)) matches.push(match[1])
– willlma
Apr 6 '17 at 18:44
@willlma Yep!..
– Nabil Kadimi
May 23 '17 at 20:00
3
3
Why not
while (match = myRegex.exec(myStr)) matches.push(match[1])– willlma
Apr 6 '17 at 18:44
Why not
while (match = myRegex.exec(myStr)) matches.push(match[1])– willlma
Apr 6 '17 at 18:44
@willlma Yep!..
– Nabil Kadimi
May 23 '17 at 20:00
@willlma Yep!..
– Nabil Kadimi
May 23 '17 at 20:00
add a comment |
Using your code:
console.log(arr[1]); // prints: abc
console.log(arr[0]); // prints: format_abc
Edit: Safari 3, if it matters.
add a comment |
Using your code:
console.log(arr[1]); // prints: abc
console.log(arr[0]); // prints: format_abc
Edit: Safari 3, if it matters.
add a comment |
Using your code:
console.log(arr[1]); // prints: abc
console.log(arr[0]); // prints: format_abc
Edit: Safari 3, if it matters.
Using your code:
console.log(arr[1]); // prints: abc
console.log(arr[0]); // prints: format_abc
Edit: Safari 3, if it matters.
answered Jan 11 '09 at 7:27
eyelidlessness
50.1k118190
50.1k118190
add a comment |
add a comment |
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
var myRegEx = /clear bal.+?(d+.?d{2})/gi;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);add a comment |
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
var myRegEx = /clear bal.+?(d+.?d{2})/gi;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);add a comment |
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
var myRegEx = /clear bal.+?(d+.?d{2})/gi;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
var myRegEx = /clear bal.+?(d+.?d{2})/gi;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
var myRegEx = /clear bal.+?(d+.?d{2})/gi;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
var myRegEx = /clear bal.+?(d+.?d{2})/gi;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = ;
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);edited Jun 22 '17 at 20:38
Nisse Engström
4,10892034
4,10892034
answered Nov 25 '16 at 9:46
Jack
6617
6617
add a comment |
add a comment |
Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:
/bformat_(.*?)b/
(But, of course, I'm not sure because I don't know the context of the regex.)
it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
– nickf
Jan 11 '09 at 12:04
Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
– PEZ
Jan 11 '09 at 12:21
add a comment |
Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:
/bformat_(.*?)b/
(But, of course, I'm not sure because I don't know the context of the regex.)
it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
– nickf
Jan 11 '09 at 12:04
Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
– PEZ
Jan 11 '09 at 12:21
add a comment |
Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:
/bformat_(.*?)b/
(But, of course, I'm not sure because I don't know the context of the regex.)
Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:
/bformat_(.*?)b/
(But, of course, I'm not sure because I don't know the context of the regex.)
edited May 23 '17 at 12:34
Community♦
11
11
answered Jan 11 '09 at 10:39
PEZ
13.5k53457
13.5k53457
it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
– nickf
Jan 11 '09 at 12:04
Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
– PEZ
Jan 11 '09 at 12:21
add a comment |
it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
– nickf
Jan 11 '09 at 12:04
Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
– PEZ
Jan 11 '09 at 12:21
it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
– nickf
Jan 11 '09 at 12:04
it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
– nickf
Jan 11 '09 at 12:04
Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
– PEZ
Jan 11 '09 at 12:21
Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
– PEZ
Jan 11 '09 at 12:21
add a comment |
/*Regex function for extracting object from "window.location.search" string.
*/
var search = "?a=3&b=4&c=7"; // Example search string
var getSearchObj = function (searchString) {
var match, key, value, obj = {};
var pattern = /(w+)=(w+)/g;
var search = searchString.substr(1); // Remove '?'
while (match = pattern.exec(search)) {
obj[match[0].split('=')[0]] = match[0].split('=')[1];
}
return obj;
};
console.log(getSearchObj(search));
add a comment |
/*Regex function for extracting object from "window.location.search" string.
*/
var search = "?a=3&b=4&c=7"; // Example search string
var getSearchObj = function (searchString) {
var match, key, value, obj = {};
var pattern = /(w+)=(w+)/g;
var search = searchString.substr(1); // Remove '?'
while (match = pattern.exec(search)) {
obj[match[0].split('=')[0]] = match[0].split('=')[1];
}
return obj;
};
console.log(getSearchObj(search));
add a comment |
/*Regex function for extracting object from "window.location.search" string.
*/
var search = "?a=3&b=4&c=7"; // Example search string
var getSearchObj = function (searchString) {
var match, key, value, obj = {};
var pattern = /(w+)=(w+)/g;
var search = searchString.substr(1); // Remove '?'
while (match = pattern.exec(search)) {
obj[match[0].split('=')[0]] = match[0].split('=')[1];
}
return obj;
};
console.log(getSearchObj(search));
/*Regex function for extracting object from "window.location.search" string.
*/
var search = "?a=3&b=4&c=7"; // Example search string
var getSearchObj = function (searchString) {
var match, key, value, obj = {};
var pattern = /(w+)=(w+)/g;
var search = searchString.substr(1); // Remove '?'
while (match = pattern.exec(search)) {
obj[match[0].split('=')[0]] = match[0].split('=')[1];
}
return obj;
};
console.log(getSearchObj(search));
answered Jun 27 '15 at 18:47
Pawel Kwiecien
212
212
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f432493%2fhow-do-you-access-the-matched-groups-in-a-javascript-regular-expression%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown