正则表达式修剪前导/尾随逗号:,aa,bb,cc,
我正在尝试从以下字符串中捕获aa,bb,cc
:
,aa,bb,cc,
aa,bb,cc,
,aa,bb,cc
aa,bb,cc
我的计划是:
- 匹配行锚点的开头,或锚点后跟逗号
- 捕获直到行锚点的末尾,或逗号后跟行尾锚点
我得到的最接近的是: (?:^,|^)(.*)(?:$|,$)
,但这包括尾随捕获组中的逗号:
,aa,bb,cc, -> aa,bb,cc,
aa,bb,cc, -> aa,bb,cc,
,aa,bb,cc -> aa,bb,cc
aa,bb,cc -> aa,bb,cc
为什么它不起作用,以及什么是正确的解决方案?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
Try this
这似乎有效:
^,*(.*?),*$
关键思想是懒惰的星号
*?
因为我想要尾随逗号(甚至多个尾随逗号,我假设) 与最后一个,*
匹配,而不是在括号内匹配。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.