是否有一个正则表达式可以替换分隔列表中的数字?
我有一个字符串,范围可以从空字符串到逗号分隔数字的任意列表。例如: "1,2,3"
不幸的是,当我编写代码来删除一个元素时,我有一堆 if 语句——主要是为了处理它是否是第一个、最后一个或唯一的元素在列表中。我一直在想必须有更好的方法!
例如,我需要能够删除以下列表中的元素“2
”:
"1,2,3"
"1,3,2"
"2,1,3"
"2"
"12,2,21"
""
I have a string that can range from the empty string to an arbitrary list of comma delimited numbers. For example: "1,2,3"
Unfortunately as I write the code to remove an element I have a bunch of if statements--mainly to deal if it is the first, last, or only element in the list. I keep thinking there has got to be a better way!
For example, I would need to be able to remove the element '2
' in the following lists:
"1,2,3"
"1,3,2"
"2,1,3"
"2"
"12,2,21"
""
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该做你想要的:
This should do what you want:
删除(请参阅下面的替换)
我找不到要删除的简单单个表达式,因此似乎最好的办法就是按顺序匹配每个模式:
有点冗长,但非常易读。
更换
Removing (see below for replacing)
I couldn't find a simple single expression to remove, so it seems the best thing is just to match each of the patterns in sequence:
A little verbose, but very readable.
Replacing