正则表达式替换重复模式

regex replace repeating patterns

如何使用正则表达式替换下面的字符串

var str="(adj., adv., part.) with or caution. (n.) difficult be etc., And. extreme care.";

str = str.replace(/(\w+\.)/, "**");

(*adj.*, *adv.*, *part.*) with or caution. (*n.*) difficult be etc., And. extreme care.

\w+. is always in (), and may be seperated by a comma and space when there are more than one.

您可以匹配具有您需要匹配的格式的字符串,然后将匹配传递给回调以用星号包裹 \w+\. 部分:

str = str.replace(/\(\w+\.(?:\s*,\s*\w+\.)*\)/g, function (m) { 
   return m.replace(/\w+\./g, "*$&*"); 
});

JS 演示:

var str="(adj., adv., part.) with or caution. (n.) difficult be etc., And. extreme care.";
console.log(str.replace(/\(\w+\.(?:\s*,\s*\w+\.)*\)/g, function (m) { 
  return m.replace(/\w+\./g, "*$&*"); 
}));

正则表达式是

/\(\w+\.(?:\s*,\s*\w+\.)*\)/g

regex demo。注意 g 修饰符,它使引擎搜索字符串中的所有匹配项。

详情

  • \( - 一个 ( 字符
  • \w+\. - 1+ 个字符和
  • 之后的一个点
  • (?:\s*,\s*\w+\.)* - 0 个或多个序列
    • \s*,\s* - 包含 0+ 个空格的 ,
    • \w+\. - 1+ 个字符和
    • 之后的一个点
  • \) - 一个 ) 字符。