Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match a string up to a number in python using regular expressions?

Tags:

python

regex

I'm new to regular expressions, but I'd like to match a string up to when the numbers start.

So just say I have:

EEEE1234

Then I would like to extract only:

EEEE

I tried searching, but I find regular expressions confusing and the best way I think is through examples. Any thoughts? Also, any insight into any regex code generators or good tutorials on this?

like image 620
user1328021 Avatar asked May 05 '26 22:05

user1328021


2 Answers

Use \D to mean "not a digit":

r"^\D+"

Example:

import re

s = "EEEE1234"
print re.match(r"^\D+",s).group(0)

See it working online: ideone

You've already got some recommendations for tutorials, but I'd like to also add that if you haven't yet seen the documentation for the re module, you should bookmark that and read that after you've read a more basic tutorial. The documentation is not beginner level but it has some very useful tips that are specific to using regular expressions in Python, and there also some examples near the end.

like image 191
Mark Byers Avatar answered May 08 '26 11:05

Mark Byers


  • \d             = one digit (numbers 0 through 9)
  • \D             = one non-digit
  • \D+           = one or more non-digits
  • \D+\d       = one or more non-digits followed by one digit
  • (\D+)\d   = one or more non-digits captured in a group followed by one digit

So, if you have a string

str = 'EEEE1234'

then you can import re and use re.match to match the regular expression on the string:

re.match(r'(\D+)\d', str)

This will get you a match object, from which you can extract the contents of the group:

re.match(r'(\D+)\d', str).group(1)

This will contain EEEE.

like image 23
rid Avatar answered May 08 '26 12:05

rid