需要使用正则表达式来匹配数字,并去除开头的零。

huangapple go评论62阅读模式
英文:

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:

https://regexr.com/78tih

英文:

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:

https://regexr.com/78tih

huangapple
  • 本文由 发表于 2023年2月23日 22:03:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定