javascript - 如何在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 来执行此操作。
谁能帮我解决这个问题?
解决方案
将正则表达式而不是字符串传递给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);
解释:
(?<!)
表示消极的向后看\d
in(?<!\d)
代表一个数字 (0-9);
从字面上匹配分号;
(?!)
是负前瞻
推荐阅读
- regex - 正则表达式 - 匹配需要'$',但这也意味着每个新行都会匹配,还有其他解决方案吗?
- python - TensorFlow数据集:地图前洗牌(map_and_batch)?
- sql - DAX - 在 SUMMARIZE 上应用 SUM
- generics - 为什么 impl 不在范围内
- haskell - 如何将函数应用于 Haskell 列表中的每个元素?
- javascript - IF/Else 条件对 addEventListener/removeEventListener 没有影响
- android - 折叠工具栏标题未居中
- javascript - JQuery 解析 XML 数据较慢
- json - 带有异步管道的 Angular 6 模板
- html - 是否可以链接到 HTML 页面的第 n 个字符?