将字符串单词与$或!等特殊字符匹配并更换它们

时间:2020-03-18 11:27:13

标签: javascript regex

需要对输入字符串进行如下处理-

// 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>'

尽管我已经设法使用循环来做到这一点,但是对了解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)}>`;
});

我被RegEx困住了,无法正确匹配具有“ $$ [a-zA-Z0-9] $$”或“ !! [a-zA-Z0-9] !!”等值的单词。 >

我的方法是结合word matchmatch replacement

3 个答案:

答案 0 :(得分:5)

您可以使用:

str = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');

RegEx Demo

RegEx详细信息:

  • (!!|\$\$)匹配!!$$并在#1组中捕获
  • ([\w-]+)匹配1个以上的单词或连字符,并捕获在第2组中
  • \1:确保字符串以与#1组相同的开始定界符结束
  • 替换<$2>,用于在<>
  • 的#2组中包装字符串

代码:

const str = 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$';

const res = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');

console.log(res);
//=> My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>

答案 1 :(得分:1)

代码

[!,$]{2}[A-Za-z0-9]+[!,$]{2}

答案 2 :(得分:1)

您可以尝试以下方法:

// Input string - 
const str = 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$'
const result = str.replace(/[!$]{2}(\S+)[!$]{2}/g,"<$1>")
console.log(result)

// Processed result
// My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>