var r = /(^|[^*])(\*)([^*]|$)/;
r.test('This is an ex*am*ple'); // true
r.test('This is an ex**am**ple'); // false
r.test('*This is an example'); // true
r.test('This is an example*'); // true
r.test('*'); // true
r.test('**'); // false
いずれの場合も、一致したアスタリスクはキャプチャ グループ 2 にあります。
完全な解決策として、正規表現を使用しない:
function findAllSingleChar(str, chr) {
var matches = [], ii;
for (ii = 0; ii < str.length; ii++) {
if (str[ii-1] !== chr && str[ii] === chr && str[ii+1] !== chr) {
matches.push(ii);
}
}
return matches.length ? matches : false;
}
findAllSingleChar('This is an ex*am*ple', '*'); // [13, 16]
findAllSingleChar('This is an ex**am**ple', '*'); // false
findAllSingleChar('*This is an example', '*'); // [0]
findAllSingleChar('This is an example*', '*'); // [18]
findAllSingleChar('*', '*'); // [0]
findAllSingleChar('**', '*'); // false