正则表达式查找第 n 个逗号并删除逗号和值

Regex to find the nth comma and remove the comma as well as the value

正在尝试删除第 3 个逗号和逗号之后的值

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

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

您可以使用

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

替换为 </code> 以恢复捕获的第 1 组值。见 <a href="https://regex101.com/r/oMC55A/1" rel="nofollow noreferrer">regex demo</a>.</p> <p><em>详情</em>:</p> <ul> <li><code>^ - 字符串开头

  • ([^,]*(?:,[^,]*){2}) - 第 1 组:
  • [^,]* - 逗号以外的零个或多个字符
  • (?:,[^,]*){2} - 出现两次逗号,然后是逗号以外的零个或多个字符
  • , - 逗号
  • [^,]* - 除逗号外的零个或多个字符。
  • 在此处应用惰性匹配概念并在第 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.