需要处理输入字符串如下 -
// Input string -
'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$'
// Processed string
'My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>'
Run Code Online (Sandbox Code Playgroud)
虽然,我已经设法使用循环来做到这一点,但对了解 RegEx 方法感兴趣。这是我实验的当前状态(在非工作状态下)-
const regex = /\b(\w*([a-zA-Z])|([\!]{2}[a-zA-Z][\!]{2})\w*)\b/g;
// str is holding the input string
str.replace(regex, (match) => {
return `<${match.substring(2, match.length - 2)}>`;
});
Run Code Online (Sandbox Code Playgroud)
我坚持使用 RegEx 来正确匹配具有“$$[a-zA-Z0-9]$$”或“!![a-zA-Z0-9]!!”之类的值的单词。
您可以使用:
str = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');
Run Code Online (Sandbox Code Playgroud)
正则表达式详情:
(!!|\$\$)在第 1 组中匹配!!或$$捕获([\w-]+) 匹配 1 个以上的单词或连字符并在第 2 组中捕获\1:确保字符串以与组 #1 中相同的起始分隔符结尾<$2>将第 2 组中的字符串包裹在<和>代码:
str = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |