Kreuzade
Kreuzade

Reputation: 777

Match number with variable number of digits

I am trying to determine if a string matches a regular expression pattern:

expected = re.compile(r'session \d+: running')
string = "session 1234567890: running"
re.match(expected, string)

However, re.match() always returns None. Am I trying to match the decimals incorrectly? The number should be 10 digits but I would like to cover the case that it is more or less digits.

EDIT: The string parameter is actually a result of a previous match:

expected = re.compile(r'session \d+: running')
found = re.match(otherRegex, otherString)
re.match(expected, found.groups()[0])

When I print the type of found.groups()[0] it prints class str and when I print found.groups()[0], it prints the string I expect: "session 1234567890: running". Could this be why it is not working for me?

Upvotes: 0

Views: 2161

Answers (2)

Kreuzade
Kreuzade

Reputation: 777

In my question I had shortened the string to the parts that were relevant. The actual string had:

expected = re.compile(r'session \d+: running task(s)')
str = "session 1234567890: running(s)"
re.match(expected, str)

The reason there were never matches is because the '(' and ')' characters are special characters and I needed to escape them. The code is now:

expected = re.compile(r'session \d+: running task\(s\)')
str= "session 1234567890: running(s)"
re.match(expected, str)

Sorry for the confusion

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

No it doesn't, it works fine for me:

In [219]: strs = "session 1234567890: running"

In [220]: expected = re.compile(r'session \d+: running')

In [221]: x=re.match(expected, strs)

In [222]: x.group()
Out[222]: 'session 1234567890: running'

Upvotes: 1

Related Questions