Regex to trim leading/trailng commas: ,aa,bb,cc,

假如想象 提交于 2019-12-13 04:13:52

问题


I'm trying to capture aa,bb,cc from the following strings:

,aa,bb,cc,
aa,bb,cc,
,aa,bb,cc
aa,bb,cc

My plan was to:

  1. Match the start of line anchor, or the anchor followed by a comma
  2. Capture until the end of line anchor, or a comma followed by the end of line anchor

The closest I've got is: (?:^,|^)(.*)(?:$|,$), but that includes trailing commas in the capture group:

,aa,bb,cc, -> aa,bb,cc,
aa,bb,cc,  -> aa,bb,cc,
,aa,bb,cc  -> aa,bb,cc
aa,bb,cc   -> aa,bb,cc

Why isn't it working, and what's the right solution?


回答1:


Try this

^,*(?<trimmed>.*?),*$



回答2:


This seems to work: ^,*(.*?),*$

The key idea is the lazy star *? because I want trailing commas (and even multiple trailing commas, I'm assuming) to be matched by the last ,* instead of being matched inside the parentheses.



来源:https://stackoverflow.com/questions/9252960/regex-to-trim-leading-trailng-commas-aa-bb-cc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!