Help us understand the problem. What is going on with this article?

JavaScriptの正規表現でキャプチャを使う

More than 1 year has passed since last update.

以下のような文字列からhttps://...pngの部分を取り出したいとする。

start"Url":"https://a/b/aaa.png","Url":"https://a/b/bbb.png","Url":"https://a/b/ccc.png"end

phpであればpreg_match_allで$result[1]に配列で格納される。

$str = 'start"Url":"https://a/b/aaa.png","Url":"https://a/b/bbb.png","Url":"https://a/b/ccc.png"end';

preg_match_all('/"(https.+?)"/', $str, $result);

print_r($result);

=>
Array
(
    [0] => Array
        (
            [0] => "https://a/b/aaa.jp"
            [1] => "https://a/b/bbb.jp"
            [2] => "https://a/b/ccc.jp"
        )

    [1] => Array
        (
            [0] => https://a/b/aaa.jp
            [1] => https://a/b/bbb.jp
            [2] => https://a/b/ccc.jp
        )

)

Javascriptもstr.matchで簡単に取れると考えてましたが。。。

let str = 'start"Url":"https://a/b/aaa.png","Url":"https://a/b/bbb.png","Url":"https://a/b/ccc.png"end';

let result = str.match(/"(https.+?)"/g);
console.log(result);

=>
[ '"https://a/b/aaa.png"',
  '"https://a/b/bbb.png"',
  '"https://a/b/ccc.png"']

matchでは取り出したい文字にダブルクォートがついた形でしか取り出せない。
なのでRegExp.execを使う。

let str = 'start"Url":"https://a/b/aaa.png","Url":"https://a/b/bbb.png","Url":"https://a/b/ccc.png"end';

let match;
let matches = [];
while (match = regexp.exec(str)) {
  matches.push(match[1]);
}
console.log(matches);

=>
[ '"https://a/b/aaa.png"',
  '"https://a/b/bbb.png"',
  '"https://a/b/ccc.png"']

最初はこのexecの繰り返しで何で取得できる値が変わっていくのかが理解できませんでした。
mozillaのドキュメントを読むと正規表現オブジェクトのlastIndexプロパティの値から検索を始めると書いてました。つまりexecを実行する度に正規表現オブジェクトのlastIndexの値が更新されていくんですね。
ドキュメントにもそう書いておいて欲しかった。。。

MDN: developer.mozilla.org

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした