如何使用正则表达式查找数字并排除括号中的数字
我正在尝试编写一个正则表达式模式,该模式将在字符串中查找带有两个前导 00 的数字,并将其替换为单个 0。问题是我想忽略括号中的数字,但我不知道如何做这个。
例如,对于字符串:
Somewhere 001 (2009)
我想返回:
Somewhere 01 (2009)
我可以使用 [00] 进行搜索来查找第一个 00,并替换为 0 但问题是 (2009) 变成了 (209) 我不想要的。我只想用 (2009) 替换 (209),但我试图修复的字符串中可能已经有一个有效的 (209)。
任何帮助将不胜感激!
I'm trying to write a regex pattern that will find numbers with two leading 00's in it in a string and replace it with a single 0. The problem is that I want to ignore numbers in parentheses and I can't figure out how to do this.
For example, with the string:
Somewhere 001 (2009)
I want to return:
Somewhere 01 (2009)
I can search by using [00] to find the first 00, and replace with 0 but the problem is that (2009) becomes (209) which I don't want. I thought of just doing a replace on (209) with (2009) but the strings I'm trying to fix could have a valid (209) in it already.
Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
搜索一个非数字(或行首),后跟两个零,后跟一个或多个数字。
如果数字有三个前导零怎么办?替换后你希望它有多少个零?如果您想捕获所有前导零并将其替换为 1:
Search one non digit (or start of line) followed by two zeros followed by one or more digits.
What if the number has three leading zeros? How many zeros do you want it to have after the replacement? If you want to catch all leading zeros and replace them with just one:
理想情况下,您会使用负向查找,但您的正则表达式引擎可能不支持它。这是我在 JavaScript 中要做的事情:
这将替换前面没有括号或其他数字的任何零字符串。如果您还使用十进制数字,请将字符类更改为
[^(\d.]
。Ideally, you'd use negative look behind, but your regex engine may not support it. Here is what I would do in JavaScript:
That will replace any string of zeros that is not preceded by parenthesis or another digit. Change the character class to
[^(\d.]
if you're also working with decimal numbers.