Regex to Extract All Matches from String Using Regexp.Exec

RegEx to extract all matches from string using RegExp.exec

Continue calling re.exec(s) in a loop to obtain all the matches:

var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';
var m;

do {
m = re.exec(s);
if (m) {
console.log(m[1], m[2]);
}
} while (m);

Try it with this JSFiddle: https://jsfiddle.net/7yS2V/

Extract number and text from string with RegExp exec Javascript

You can use the below regex to remove all non alphanumeric characters.

let string = '171Toberin, [171]Toberin or [171]';

console.log(string.replace(/[^a-zA-Z0-9]/g, ''));

Javascript: How to get multiple matches in RegEx .exec results

exec() is returning only the set of captures for the first match, not the set of matches as you expect. So what you're really seeing is $0 (the entire match, "a") and $1 (the first capture)--i.e. an array of length 2. exec() meanwhile is designed so that you can call it again to get the captures for the next match. From MDN:

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property).

RegEx to find all matches, not just one

You can use

$s = "123 234 345 567"
Select-String '\d{3}' -input $string -AllMatches | % {$_.matches.value}

See demo:
Sample Image

Notes:

  • With \d{3} pattern, you can extract three consecutive digits from any context
  • With -AllMatches, you can extract all multiple occurrences/matches
  • % {$_.matches.value} will get the matched values as strings.

The pattern can also be defined in other ways:

  • (?<!\d)\d{3}(?!\d) pattern lets you extract three consecutive digits that are not enclosd with other digits
  • (?<!\d\.?)\d{3}(?!\.?\d) - to match only integer numbers consisting of 3 digits in messed-up contexts
  • (?<!\S)\d{3}(?!\S) - match three digit chunks in between whitespaces or start/end of string
  • \b\d{3}\b - match three digit numbers as whole words (not enclosed with letters, digits or underscores).

JavaScript regex get all matches in a string

You need to use g (for global) identifier as in

var identifiers = mediaQuery.match(/\.(.*?)}/g);

See the documentation here. Also, as mentioned in the comments by @chiliNUT, you need to use .*? instead of .* in order for your regex not be greedy. See here for more.

Regex exec only returning first match

RegExp.exec is only able to return a single match result at once.

In order to retrieve multiple matches you need to run exec on the expression object multiple times. For example, using a simple while loop:

var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;

var match;
while ((match = ptrn.exec(input)) != null) {
console.log(match);
}

This will log all matches to the console.

Note that in order to make this work, you need to make sure that the regular expression has the g (global) flag. This flag makes sure that after certain methods are executed on the expression, the lastIndex property is updated, so further calls will start after the previous result.

The regular expression will also need to be declared outside of the loop (as shown in the example above). Otherwise, the expression object would be recreated on every iteration and then the lastIndex would obviously reset every time, resulting in an infinite loop.

How do I extract only part of a matched string with regex?

Yes, a capture group does this. You don't see it in your array because you've used String#match and the g flag. Either remove the g flag (and take the second entry from the array, which is the first capture group):

console.log('https://twitter.com/pixelhenk/status/891303699204714496'.match(/\/status\/(\d+)/)[1]);

How to extract all matches with regex in VSCode snippets and return them in a specific format?

try these

"${TM_FILEPATH/[^\\[]*\\[([^\\]]+)\\][^\\[]*/$1, /g}"

or

"${TM_FILEPATH/[^\\[]*\\[([^\\]]+)\\][^\\[]*\\[([^\\]]+)\\][^\\[]*\\[([^\\]]+)\\][^\\[]*/$1, $2, $3/}"


Related Topics



Leave a reply



Submit