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?
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.
\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 digitSo, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With