【问题标题】:Regex to find the nth comma and remove the comma as well as the value正则表达式查找第 n 个逗号并删除逗号以及值
【发布时间】:2022-01-13 13:21:42
【问题描述】:

尝试删除第三个逗号和逗号之后的值

a,b,c,d,e,f 
g,h,i,asj,k,l

如何编写正则表达式来查找 3 个逗号并删除 ,d 和 ,asj ?我试过这个/(?=(,[^,]{0,3}\n 但无法让它工作

【问题讨论】:

  • 为什么你的正则表达式中有\n?这将匹配换行符,但您没有换行符。
  • ^([^,]*(?:,[^,]*){2}),[^,]* > $1 (demo)
  • {0,3} 表示 0 到 3 个匹配项,而不是 3 个匹配项。
  • 您的( 没有匹配的)。这甚至不是一个完整的正则表达式。

标签: regex regexp-replace


【解决方案1】:

在这里应用惰性匹配概念并在第 3 个逗号左右之后删除值,请尝试使用所示示例编写和测试的正则表达式。

^((?:.*?,){3})[^,]*,(.*)$

Online demo for above regex

说明:为上述正则表达式添加详细说明。

^((?:.*?,){3})  ##Matching from starting of value and creating 1st capturing group which has everything till 3rd comma in it. Using lazy match .*?
                ##to make sure its not a greedy match(in a non-capturing group, to avoid creating 2 groups).
[^,]*,          ##Matching everything till next occurrence of comma including that comma.
(.*)$           ##Creating 2nd capturing group which has everything in it till end of the value.

【讨论】:

    【解决方案2】:

    你可以使用

    ^([^,]*(?:,[^,]*){2}),[^,]*
    

    替换为 $1 以恢复捕获的 Group 1 值。请参阅regex demo

    详情

    • ^ - 字符串开头
    • ([^,]*(?:,[^,]*){2}) - 第 1 组:
    • [^,]* - 零个或多个除逗号以外的字符
    • (?:,[^,]*){2} - 出现两次逗号,然后出现零个或多个逗号以外的字符
    • , - 逗号
    • [^,]* - 零个或多个除逗号以外的字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      相关资源
      最近更新 更多