问题
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:
- Match the start of line anchor, or the anchor followed by a comma
- 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