用于从逗号分隔的字符串中删除项目的正则表达式? [英] Regex for removing an item from a comma-separated string?

查看:59
本文介绍了用于从逗号分隔的字符串中删除项目的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的字符串:1,2,3,11"

Say I have a string like this: "1,2,3,11"

像这样的简单正则表达式将在字符串中找到一个数字:(?<=^|,)1(?=,|$) - 这将正确地找到1"(即不是11"中的第一个1").

A simple regex like this will find a number in the string: (?<=^|,)1(?=,|$) - this will correctly find the "1" (ie. not the first "1" in "11").

但是,要从字符串中删除一个数字,并在每个数字之间使用逗号正确格式化字符串,我需要只包含一个相邻的逗号.例如,匹配 1,, 2,,11.

However, to remove a number from the string, leaving the string properly formatted with commas in between each number, I need to include one adjacent comma only. For example, matching 1,, 2, or ,11.

所以诀窍是匹配一个逗号,在数字的任一侧,但忽略相反侧的逗号(如果有的话).有人可以帮我解决这个问题吗?

So the trick is to match one comma, on either side of the number, but to ignore the comma on the opposite side (if there is one). Can someone help me with this?

Ed:应该提到这必须在代码中完成,而不是使用外部工具.

Ed: Should mention this has to be done in code, not using external tools.

推荐答案

从字符串中删除一个数字,正确保留字符串每个数字之间用逗号格式化

to remove a number from the string, leaving the string properly formatted with commas in between each number

尝试使用以下 regex 并替换为空字符串.

Try using following regex and replace with empty string.

\b1\b,|,\b1\b$

<小时>

使用sed

sed -e 's/\b1\b/,/g' -e 's/,,//g'

这篇关于用于从逗号分隔的字符串中删除项目的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆