英文:
Need to match the digit using regex by removing the initial zeroes
问题
I want to match initial character in the string by using regex to ignore the symbol "+" or "-" and consuming only 0 before any digit between 1 to 9.
Example
+004200
004200
Here, in the above example, I want to match only +4200 and 4200 respectively, by removing the initial zeroes.
I tried to solve it, by using the expression ^[^-+]\0+, but it is not matching anything. By analysing further, I figured that the expression [^-+] is still consuming the value. Can anybody suggest the correct approach?
英文:
I want to match initial character in the string by using regex to ignore the symbol "+" or "-" and consuming only 0 before any digit between 1 to 9.
Example
+004200
004200
Here, in the above example, I want to match only +4200 and 4200 respectively, by removing the initial zeroes.
I tried to solve it, by using the expression ^[^-+]\0+, but it is not matching anything. By analysing further, I figured that the expression [^-+] is still consuming the value. Can anybody suggest the correct approach?
答案1
得分: 1
如果您想去掉可选的零并保留至少一个数字1-9:
([+-]?)0*([1-9]\d*)
解释
([+-]?)捕获组1,匹配可选的+或-0*匹配可选的零([1-9]\d*)捕获组2,匹配数字1-9和可选的数字0-9
查看 regex101 演示。
在替换中使用捕获组1和捕获组2
如果至少应该有1个零存在:
([+-]?)0+([1-9]\d*)
查看另一个 regex101 演示。
英文:
If you want to remove optional zeroes and keep at least a single digit 1-9 after it:
([+-]?)0*([1-9]\d*)
Explanation
([+-]?)Capture group 1, match an optional+or-0*Match optional zeroes([1-9]\d*)Capture group 2, match a digit 1-9 and optional digits 0-9
See a regex101 demo.
In the replacement use group 1 and group 2
If there should be at least 1 zero present:
([+-]?)0+([1-9]\d*)
See another regex101 demo.
答案2
得分: 0
以下是要翻译的内容:
Your first capture group ($1 or \\1) will contain the +/- if present, and the second group ($2 or \\2) will contain the number without leading 0s
As a note - you have to escape - with \ when it's in a character group [] since it is used to denote sequences - [a-z] means all letters between a and z.
See this example here:
英文:
I would look at this:
/([+\-])*[0]*(\d+)/g
Your first capture group ($1 or \\1) will contain the +/- if present, and the second group ($2 or \\2) will contain the number without leading 0s
As a note - you have to escape - with \ when it's in a character group [] since it is used to denote sequences - [a-z] means all letters between a and z.
See this example here:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论