Home > Software design >  Regex - Regular expression for counting no.of digits between alphabets
Regex - Regular expression for counting no.of digits between alphabets

Time:10-14

Need to construct a regular expression that counts numbers between alphabets.

schowalte3rguss77ie85  - 2
xyz1zyx - 1
x1y1z1 - 2

I have constructed this . But this doesn't work for case 3. [[a-z] [0-9] [a-z]]* Any help would be appreciated. Thanks in advance.

CodePudding user response:

If you want a count only, the last part should be a lookahead assertion.

If you want to also match uppercase chars, you can make the pattern case insensitive.

[a-z]\d (?=[a-z])

Explanation

  • [a-z] Match a single char a-z
  • \d Match 1 digits
  • (?=[a-z]) Positive lookahead, assert a char a-z to the right

Regex demo

CodePudding user response:

You can use

(?<=[^\W\d_])\d (?=[^\W\d_])

See the regex demo. If you want to only support ASCII letters, replace [^\W\d_] (that matches any Unicode letter) with [a-zA-Z].

Details:

  • (?<=[^\W\d_]) - immediately before the current location, there must be a letter
  • \d - one or more digits
  • (?=[^\W\d_]) - immediately after the current location, there must be a letter.
  • Related