import re
= 'R1C2_row62_col24.png'
some_string = re.match(r".*row(\d+)_col(\d+).*.png", some_string)
m = int(m.group(1))
row = int(m.group(2))
col assert row == 62
assert col == 24
Regex
Suppose we need to extract row
and col
from a string ‘R1C2_row62_col24.png’:
or suppose we want to extract a string from a name ‘some_class_name_123.jpg’:
import re
= 'some_class_name_123.jpg'
some_string = re.match(r"(.+)_\d+.jpg", some_string)
m assert m.group(1) == 'some_class_name'
Test here https://regex101.com/
Character | Action |
---|---|
. |
any character |
\d |
only numbers (if we need decimal point user a backslash (.) |
? |
Zero or one character |
+ |
One or many |
* |
Any character count |
Good tutorial.