Marius
Marius

Reputation: 3643

Regex that matches a string that starts with whitespace and has only digits after

I need a regex that will match lines like:

    123
  12345
1234567

So I know the maximum length of a string (7) and that string can contain only digits and whitespaces at the beginning.

I have tried this one: [ 0-9]{7} but this one will match strings like 12 34

Upvotes: 1

Views: 4856

Answers (2)

Tarang Arora
Tarang Arora

Reputation: 144

^(?=[\s\d]{7}$)\s*\d*$

looks good and will match on all example cases given in question while reducing it's FP probability near to zero.

Though, i found some cases when it might FP, specially when the string is made up of 7 spaces only or 7 newlines, or 7 new tabs, which i feel something not expected.

Demo: https://regex101.com/r/eH3jM6/2

So, in order to make it perfect, let's modify it:

                          ^(?=[ \d]{7}$) {0,6}\d*$

For more reference: Check

https://www.talentcookie.com/2015/07/lets-practice-regular-expression/ https://www.talentcookie.com/2016/01/some-useful-regular-expression-terminologies/

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

The [ 0-9]{7} will match 7 digits or spaces in any order and this pattern can return partial matches since it is not anchored at the start/end of the string.

You can use a lookahead restricting the length of the string, and use the sequential subpatterns:

^(?=[\s\d]{7}$)\s*\d*$

See the regex demo

The pattern breakdown:

  • ^ - start of string
  • (?=[\s\d]{7}$) - the string will be matched only if the whole string consists of whitespaces or/and digits of whole length 7
  • \s* - 0+ whitespace symbols
  • \d* - 0+ digits
  • $ - end of string.

Upvotes: 3

Related Questions