Home > Net >  Regular expression for the following pattern: "One or more spaces between a letter and a digit&
Regular expression for the following pattern: "One or more spaces between a letter and a digit&

Time:09-05

I am looking for a regular expression for the following pattern:

"One or more spaces between a letter and a digit".

For example, suppose we have the following string:

"USA 45623
China      12313
Colombia   46546"

The sequence of characters that match the desired pattern are:

" " (the single space between USA and 12312)

" " (the 6 spaces between China and 12313)

" " (the 3 spaces between Colombia and 46546).

Thank you in advance.

CodePudding user response:

You could use this regex:

(?<=[A-Za-z])  (?=\d)

which will match spaces that are after a letter (asserted by the lookbehind (?<=[A-Za-z])) and before a digit (asserted by the lookahead (?=\d)).

Demo on regex101

CodePudding user response:

To find the pattern you're looking for, you could do the following:

[A-Za-z] \s \d 

[A-Za-z] matches letters, digits and underscores. Adding the to it finds an indeterminate amount so long as the characters are contiguous.

\s matches whitespace. Adding the will enable you to match an indeterminate amount of whitespace so long as it's contiguous.

\d matches numbers only. adding the sign matches multiple digits so long as they're contiguous.

CodePudding user response:

st = '''
USA 45623 
China      12313 
Colombia   46546'''

# using \s{1,} for one or more spaces
re.findall(r'[a-zA-Z] \s{1,}\d ', st)

['USA 45623', 'China      12313', 'Colombia   46546']
  • Related