次のサンプルコードがあります。Excel式の配列があり、URLからハイパーリンクのタイトルを分離するためにregexを使用しています。これは一部では動作するようですが、他の人にはnull
を返します。Regexが結果を返すことがあり、同様の文字列にNULLを返すことがあります
私はそれがループかもしれないと思っていましたが、下の例2に示すように悪い結果も出ます。
例1:
var linkList = ['=HYPERLINK("https://example.com","Example")', '=HYPERLINK("https://example2.com","Example 2")', '=HYPERLINK("https://example3.com","Example 3")', '=HYPERLINK("https://example4.com","Example 4")'];
const url_re = /".*?"/g;
const linkName_re = /\,(".*?")/g;
linkList.forEach(function(currentValue, index, array){
+console.log(url_re.exec(currentValue));
console.log(linkName_re.exec(currentValue));
console.log("---------------------------");
});
出力:
[ '"https://example.com"',
index: 11,
input: '=HYPERLINK("https://example.com","Example")' ]
[ ',"Example"',
'"Example"',
index: 32,
input: '=HYPERLINK("https://example.com","Example")' ]
---------------------------
[ '","',
index: 32,
input: '=HYPERLINK("https://example2.com","Example 2")' ]
null
---------------------------
null
[ ',"Example 3"',
'"Example 3"',
index: 33,
input: '=HYPERLINK("https://example3.com","Example 3")' ]
---------------------------
[ '"https://example4.com"',
index: 11,
input: '=HYPERLINK("https://example4.com","Example 4")' ]
null
---------------------------
例2:
const url_re = /".*?"/g;
const linkName_re = /\,(".*?")/g;
console.log(url_re.exec('=HYPERLINK("https://example.com","Example")'));
console.log(linkName_re.exec('=HYPERLINK("https://example.com","Example")'));
console.log("---------------------------");
console.log(url_re.exec('=HYPERLINK("https://example2.com","Example 2")'));
console.log(linkName_re.exec('=HYPERLINK("https://example.com","Example 2")'));
console.log("---------------------------");
console.log(url_re.exec('=HYPERLINK("https://example3.com","Example 3")'));
console.log(linkName_re.exec('=HYPERLINK("https://example.com","Example 3")'));
console.log("---------------------------");
console.log(url_re.exec('=HYPERLINK("https://example4.com","Example 4")'));
console.log(linkName_re.exec('=HYPERLINK("https://example.com","Example 4")'));
console.log("---------------------------");
出力:
[ '"https://example.com"',
index: 11,
input: '=HYPERLINK("https://example.com","Example")' ]
[ ',"Example"',
'"Example"',
index: 32,
input: '=HYPERLINK("https://example.com","Example")' ]
---------------------------
[ '","',
index: 32,
input: '=HYPERLINK("https://example2.com","Example 2")' ]
null
---------------------------
null
[ ',"Example 3"',
'"Example 3"',
index: 32,
input: '=HYPERLINK("https://example.com","Example 3")' ]
---------------------------
[ '"https://example4.com"',
index: 11,
input: '=HYPERLINK("https://example4.com","Example 4")' ]
null
---------------------------
あなたは[正規表現101回のテスト](https://regex101.com/tests)を使用してみましたか? –
@AlanLarimerここに投稿する前に式をテストするためにRegex101を使いました。 –