推荐在线正则网站: regex101.com/
基本语法
- +?: 尽可能少的重复上一个字符 而不是继续回溯,急切结束
和“+”类似,“?*”的重复也是贪婪的。尽可能匹配多的
- ?:告诉引擎匹配前导字符0次或一次。事实上是表示前导字符是可选的。
- +:告诉引擎匹配前导字符1次或多次
- *:告诉引擎匹配前导字符0次或多次
记忆:? < + < *
1. 例子
正则:<.+?>
This is a <EM>first</EM> test
结果:
<EM>
</EM>
惰性重复,所以引擎是扩展惰性重复而不是减少,于是“<.+”现在被扩展为“<EM”
更好:<[^>]+>
2. 例子
正则:(\/~).+?(~\/)
- Target
額外住院保障/~3//~/^=~/~/~~~~~~22~/11 111/~ee~/
- result
/~3//~/
/~/~~~~~~22~/
/~ee~/
- 应用
const regText = txt => {
if (!txt) return '';
// match Text "額外住院保障/~3//~/^=~/~/~~~~~~22~/11111/~ee~/"
// to '額外住院保障<sub>3//</sub>^=~<sub>/~~~~~~22</sub>11111<sub>ee</sub>'
const regtxt = txt.match(/(\/~).+?(~\/)/gm) || [];
regtxt.map(item => {
let newItem = item.replace(/^\/~/, '<sup>');
newItem = newItem.replace(/~\/$/, '</sup>');
txt = txt.replace(item, newItem);
return item;
});
return txt;
};
正则导向的引擎。js 文本导向的引擎是不回溯的。 不支持惰性重复操作。