[英]Regex to find the nth comma and remove the comma as well as the value
尝试删除第三个逗号和逗号之后的值
a,b,c,d,e,f
g,h,i,asj,k,l
如何编写正则表达式来查找 3 个逗号并删除,d 和,asj? 我试过这个/(?=(,[^,]{0,3}\n
但无法让它工作
您可以使用
^([^,]*(?:,[^,]*){2}),[^,]*
替换为$1
以恢复捕获的 Group 1 值。 请参阅正则表达式演示。
详情:
^
- 字符串的开头([^,]*(?:,[^,]*){2})
- 第 1 组:[^,]*
- 除逗号之外的零个或多个字符(?:,[^,]*){2}
- 出现两次逗号,然后是逗号以外的零个或多个字符,
- 逗号[^,]*
- 除逗号之外的零个或多个字符。在此处应用惰性匹配概念并在第 3 个逗号左右后删除值,请尝试使用所示示例编写和测试正则表达式。
^((?:.*?,){3})[^,]*,(.*)$
说明:为上述正则表达式添加详细说明。
^((?:.*?,){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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.