首页 > 解决方案 > 如何在Javascript中有条件地拆分?

问题描述

我有一个这样的字符串

"Earth Continuity (4;1) due to;Electric safety devices(4;2) due to;Electric safety devices(4;2) Top Final Limit Switch"

我需要拆分这个字符串,输出应该看起来像 Bello

[Earth Continuity (4;1) due to,Electric safety devices(4;2) due to,
Electric safety devices(4;2) Top Final Limit Switch]

这里的分隔符是;,但是如果一个数字出现在分隔符之前和之后,例如(4;5),我需要跳过拆分,因此我不能使用拆分,;而是需要 Regexp 来执行此操作。

谁能帮我解决这个问题?

标签: javascriptregex

解决方案


将正则表达式而不是字符串传递给split函数:

var str = "Earth Continuity (4;1) due to;Electric safety devices(4;2) due to;Electric safety devices(4;2) Top Final Limit Switch";
var splitStr = str.split(/(?<!\d);(?!\d)/)

console.log(splitStr);

解释:

  • (?<!)表示消极的向后看
  • \din(?<!\d)代表一个数字 (0-9)
  • ;从字面上匹配分号;
  • (?!)是负前瞻

推荐阅读