繁体   English   中英

正则表达式拆分字符串和离开分隔符

[英]RegEx Split String and Leave Delimiter

我正在尝试拆分字符串并保持分隔符不变。 我已经很接近了,但我无法完全弄清楚。 我在 Stack Overflow 上找到了很多示例,但我仍然遇到了一个我无法弄清楚的问题。 这是代码:

"This is a string with ${G:VarSome:G} text".split(/\$\{(.+?(}\(.+?\)|}))/g)

上面的代码产生:

['This is a string with ', 'G:VarSome:G}', '}', ' text']

我正在寻找的结果是:

['This is a string with ', '${G:VarSome:G}', ' text']

${G:SomeVar:G} 模式是一个模板系统,其中将注入变量。 还有其他格式的变量,例如 ${G:AnotherVar:1}、${G:DifferentVar:5} 等。得到拆分字符串后,我将在系统中进行变量查找以注入相应的变量。

您在正则表达式中有一个额外的捕获组,这将为您提供一个组。

/(\$\{.+?})/g

这应该捕获提供的示例。 正则表达式101

 const result = "This is a string with ${G:VarSome:G} text".split(/(\$\{.+?})/g); console.log(result);

您可以使用此正则表达式进行拆分:

/(\${[^}]*})/

代码:

 var s = 'This is a string with ${G:VarSome:G} text'; var arr = s.split(/(\${[^}]*})/); console.log(arr);

这里:

  • \${[^}]*} :将匹配${后跟 0 个或多个非}字符后跟}

暂无
暂无

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

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