首页 > 解决方案 > 使用正则表达式捕获字符串的第二部分

问题描述

我有一组字符串

字符串以 开头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');


我错过了什么?

标签: javascriptreactjsregex

解决方案


您可以尝试使用 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')));

推荐阅读