【问题标题】:Capture second part of the string using regular expression使用正则表达式捕获字符串的第二部分
【发布时间】:2021-07-12 18:15:58
【问题描述】:

我有一组字符串

字符串要么以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');


我错过了什么?

【问题讨论】:

    标签: javascript reactjs regex


    【解决方案1】:

    您可以尝试使用 OR 来分隔两个不同的匹配器。第一个匹配器查找中间的单词,而第二个匹配缺少“floor”或“door”后缀的单词。

    唯一的其他调整是用正则表达式中的第三个分组代替第二个分组:

    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')));
    

    【讨论】:

    • 嘿,谢谢它有效。如果我现在必须满足另一个字符串elevator_started_door_open_floor_10_door_b 应该返回elevator_started_door_open 使warning_withbreakdown_with 第一部分可选?
    • 在开头而不是结尾尝试另一个 OR。
    猜你喜欢
    • 2019-10-12
    • 2023-03-31
    • 1970-01-01
    • 2018-05-17
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2019-10-29
    相关资源
    最近更新 更多