Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring white space for a Regex match

Tags:

c#

.net

regex

I need to match 8 or more digits, the sequence of which can include spaces.

for example, all of the below would be valid matches.

12345678
1 2345678
12 3 45678
1234 5678
12 34567 8
1 2 3 4 5 6 7 8

At the moment I have \d{8,} but this will only capture a solid block of 8 or more digits.
[\d\s]{8,} will not work as I don't want white space to contribute to the count of chars captured.

like image 893
Greg B Avatar asked Jul 19 '10 09:07

Greg B


People also ask

How do I match a character except space in regex?

[^ ] matches anything but a space character.

What is a non-whitespace character in regex?

Non-word character: \W. Whitespace character: \s. Non-whitespace character: \S.

Does regex include whitespace?

Yes, also your regex will match if there are just spaces.

Is used for matches any non-whitespace characters?

The \S metacharacter matches non-whitespace characters. Whitespace characters can be: A space character.


1 Answers

(\d *){8,}

It matches eight or more occurrences of a digit followed by zero or more spaces. Change it to

( *\d *){8,}  #there is a space before first asterik

to match strings with spaces in the beginning. Or

(\s*\d\s*){8,}

to match tabs and other white space characters (that includes newlines too).

Finally, make it a non-capturing group with ?:. Thus it becomes (?:\s*\d\s*){8,}

like image 167
Amarghosh Avatar answered Sep 18 '22 01:09

Amarghosh