Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for all spaces before a number

Tags:

regex

I need to select via RegEx every space before a number.

I know whitespace is \s and digit is \d, but I can't figure out how to just grab the space before the number.

Sample text: John Doe 6 Jane Doe 0

It should select the spaces before 6 and 0.

Any ideas?

Thanks!

like image 438
Will M Avatar asked Jun 10 '13 15:06

Will M


People also ask

What does \d mean in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.

How do you use spaces in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


1 Answers

This regex will capture the space before any number

\s+(?=\d)

The positive look ahead (?=\d) requires that any number of whitespace characters be followed by a digit

If you want to match only spaces and not the other characters which could be represented by a \s then use:

[ ]+(?=\d)
like image 61
Ro Yo Mi Avatar answered Sep 17 '22 22:09

Ro Yo Mi