概要
ログのパースなどで、クォーテーションマークに囲まれた部分を抽出したい
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.
否定的後読みについては↓のページがわかりやすかったです。