EralpB
EralpB

Reputation: 1742

Regex don't consider spaces

I want to find n consecutive numbers in a text. I can't just allow space because that would break the count rule (n digits!). What would be the easiest way to do this?

I mean I don't want to do \d\s*\d\s*\d\s*... etc I feel there's a better way.

edit: [\d\s]{n} doesn't work because I want n digits not n characters.

Upvotes: 0

Views: 1593

Answers (2)

jmar777
jmar777

Reputation: 39699

This should work:

/^\s*(?:\d\s*){n}$/

Explanation:

  • /^\s*…$ will match a string that optionally begins with whitespace.
  • (?:…){n} creates a non-capturing group, where everything in the group will be matched n times.
  • \d\s* will match a single digit, with optional whitespace after it.

Upvotes: 3

Bohemian
Bohemian

Reputation: 425448

This requires exactly n digits:

^\D*(\d\D*){n}\D*$

or if only spaces are allowed other than digits:

^ *(\d ){n} *$

Upvotes: 1

Related Questions