繁体   English   中英

如何使用正则表达式替换部分字符串?

[英]How to use regex to replace part of string?

如何在Javascript中搜索[SM_g]randomword[SM_h].所有实例的字符串[SM_g]randomword[SM_h]. 并将其全部替换为[SM_g]randomword.[SM_h]

我也想用逗号来做。 例如-我需要能够将[SM_g]randomword[SM_h],转换为[SM_g]randomword,[SM_h]

到目前为止,这是我的代码:

const periodRegex = /\[SM_g](.*?)\[SM_h](?:[.])/g;
string_afterregex - string_initial.replace(periodRegex, /*I don't know what goes in here*/)

捕获模式,然后使用反向引用重新排序:

 const periodRegex = /(\\[SM_g].*?)(\\[SM_h])([.,])/g; var string_initial = '[SM_g]randomword[SM_h].' var string_afterregex = string_initial.replace(periodRegex, "$1$3$2"); console.log(string_afterregex); var string_initial = '[SM_g]randomword[SM_h],' console.log(string_initial.replace(periodRegex, "$1$3$2")) 

如果您受益于前瞻性,则不必使用多个正则表达式来实现所需的功能:

 const re = /\\[SM_g](?=(((?:(?!\\[SM_h]).)*)\\[SM_h])([.,]))\\1./g; const str = '[SM_g]$2$3[SM_h]'; console.log("[SM_g]WORD[SM_h], [SM_g]WORD[SM_h]. [SM_g]WORD[SM_h]".replace(re, str)); 

分解:

  • \\[SM_g] [SM_g]从字面上匹配[SM_g]
  • (?=开始积极的前瞻
    • (开始捕获#1组
      • ( CG#2开始
        • (?: NCG#1的起点,回火的点
          • (?!\\[SM_h]) 匹配下一个字符而不跳过[SM_h]
        • )* NCG#1结束,请尽可能重复
      • ) CG#2结束
      • \\[SM_h] [SM_h]从字面上匹配[SM_h]
    • ) CG#2结束
    • ( CG#3的开始
      • [.,]匹配逗号或句点
    • ) CG#4结束
  • )正向超前结束
  • \\1. 匹配CG#1匹配的内容,然后匹配一个字符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM