Home > Web Front-end > JS Tutorial > How to Extract All Matches from a String Using RegExp.exec()?

How to Extract All Matches from a String Using RegExp.exec()?

Susan Sarandon
Release: 2024-12-18 06:00:15
Original
332 people have browsed it

How to Extract All Matches from a String Using RegExp.exec()?

RegExp to Extract Multiple Matches Using RegExp.exec

To extract all matches from a string using RegExp.exec, you can continue calling re.exec(s) in a loop. The following code snippet demonstrates this:

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);
Copy after login

With the provided test string '[description:"aoeu" uuid:"123sth"]', this code will output:

description aoeu
uuid 123sth
Copy after login

Note that the regular expression used here:

  • s*: Matches optional whitespace around the colon.
  • ([^[:] ): Matches any non-whitespace sequence as the key.
  • :: Matches the literal colon.
  • ("([^"] )": Matches the value as any non-double-quote sequence enclosed in double quotes.

To test this solution, you can use the provided JSFiddle link: https://jsfiddle.net/7yS2V/.

The above is the detailed content of How to Extract All Matches from a String Using RegExp.exec()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template