javascript - 使用正则表达式捕获字符串的第二部分
问题描述
我有一组字符串
字符串以 开头warning_with_
或以 开头breakdown_with_
。我想提取出来door_cycling
,中心部分
warning_with_
或/之后的文字breakdown_with_
如果不匹配,则按原样返回字符串。
"warning_with_door_cycling_floor_n_door_b" --> regex should return ---- door_cycling
"breakdown_with_door_cycling_door_:door:" --> regex should return ---- door_cycling
"breakdown_with_door_cycling_door_a" --> regex should return ---- door_cycling
"breakdown_with_bumps_at_location" --> regex should return ---- bumps_at_location
"unknown_string" --> regex should return ---- unknown_string
到目前为止,这就是我所做的
const regex = /(warning_with_|breakdown_with_)(\w+?)(?:(_floor_|_door_).+)/;
// But it does not work for this case
"breakdown_with_bumps_at_location".replace(regex, '$2');
我错过了什么?
解决方案
您可以尝试使用 OR 来分隔两个不同的匹配器。第一个匹配器查找中间词,而第二个匹配器匹配缺少“地板”或“门”后缀的词。
唯一的其他调整是用正则表达式中的第三组替换而不是第二组:
const data = [
"warning_with_door_cycling_floor_n_door_b",
"breakdown_with_door_cycling_door_:door:",
"breakdown_with_door_cycling_door_a",
"breakdown_with_bumps_at_location",
"unknown_string"
];
const regex = /((warning_with_|breakdown_with_)(\w+?)(?:(_floor_|_door_).+))|((warning_with_|breakdown_with_))/;
data.forEach((elem) => console.log(elem.replace(regex, '$3')));
推荐阅读
- python - 如何在 Graphviz 中指定边连接到节点的位置
- java - 我的项目需要哪些接口、抽象类和类?
- asp.net-core - 在 IIS 上发布 asp.net 核心项目时出错
- python - 返回空列表的方法
- javascript - 从 Excel 公式转换为 JavaScript 的问题
- php - 未定义变量:编辑刀片中的类别
- css - 更改 v-combobox 下拉菜单的宽度
- python - 凝聚层次聚类的确定级别
- swift - 升级到 Promisekit 6 后代码变得更加臃肿
- reactjs - 错误说:“未捕获的 TypeError:path.split 不是函数”。我猜这个错误是由于 react-hook-form 更新造成的。有人知道吗?