porterhaus
porterhaus

Reputation: 469

Regex for leading zeros and exclude normal zeros

I am looking two traverse a list of alphanumerics that look like this:

0012-0103

I want to remove all leading zeros but keep the ones that belong to a given number value.

I have this which gets all the zeros:

/0*([1-9][0-9])?0/

Any suggestions. I am still review regex documentation.

Upvotes: 0

Views: 378

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

You can use the following:

\b0+

See DEMO

Explanation:

  • \b word boundary.. this will check for all the boundaries which are separated by word and non word (digits are part of word)
  • 0+ match more than one zeros

Therefore, this will match all those zeros which are not in middle..

Upvotes: 3

Mike Covington
Mike Covington

Reputation: 2157

It is difficult to give a precise answer without knowing the language and what exactly you want to do. I looked at your profile and it seems like you are probably doing this in ruby. Therefore, try this:

irb(main):001:0> string = "0012-0103"
=> "0012-0103"
irb(main):002:0> string.match(/0*([\d-]+)/).captures
=> ["12-0103"]

Upvotes: 0

Related Questions