LoginSignup
13
12

More than 5 years have passed since last update.

正規表現でクォーテーションマークに囲まれた部分を抽出

Posted at

概要

ログのパースなどで、クォーテーションマークに囲まれた部分を抽出したい

sample.log
2018/03/31 08:00 text='this is my text.'

コード

最初に考えた方法

囲まれた部分を抽出するので、RegExp#exec を利用します。

const str = "text='this is my text.'";
const regex = /='(.*?)'/;
const matched = regex.exec(str);

if (matched) {
    console.log(matched[1]);
}
output
this is my text.

ただしこの正規表現では、下記のようにエスケープされたシングルクォート「\'」が入った場合に正しく抽出できません。

sample2.log
text='this is my son\'s text.'
const str = "text='this is my son\\'s text.'";
const regex = /='(.*?)'/;
const matched = regex.exec(str);

if (matched) {
    console.log(matched[1]);
}
output
this is my son

エスケープ文字を考慮した正規表現

否定的後読み(?<!)を利用して、直前に「\」のあるシングルクォートを囲み文字としないようにします。

const str = "text='this is my son\\'s text.'";
const regex = /='(.*?)(?<!\\)'/; // <- ここ
const matched = regex.exec(str);

if (matched) {
    console.log(matched[1]);
}
output
this is my son\'s text.

否定的後読みについては↓のページがわかりやすかったです。

13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12