An old man in the sea.
An old man in the sea.

Reputation: 1518

re.search returns none for a pattern, but with a subpattern we get a result

We have the following:

string = "Your Policy gives you 18/11/21 (Noor) to 18/11/22 (Noon) 18/11/22 Comprehensive cover Sections AB,C,D,E,FGJ in your Policy booklet are the "

re.search('18/11/21 (Noor) to',string).span()

This return none type..

If I run re.search('18/11/21',string).span() then I get a result. Why does this happen?

Upvotes: 0

Views: 26

Answers (2)

9769953
9769953

Reputation: 12221

Parentheses in a regular expression are special: they indicate a capture pattern. You'll have to escape them:

>>> re.search('18/11/21 \(Noor\) to',string).span()
(22, 40)

Better yet:

>>> '18/11/21 (Noor) to' in string
True

simply yields True, and

>>> string.index('18/11/21 (Noor) to')
22

will give you the starting index in string of the pattern. Combine with len('18/11/21 (Noor) to') to obtain the span.

As long as your pattern is a simple string, there is generally no need for a regular expression.

Upvotes: 2

wiltonsr
wiltonsr

Reputation: 1027

From docs

(...) Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')', use \( or \), or enclose them inside a character class: [(], [)].

You need to escape

string = "Your Policy gives you 18/11/21 (Noor) to 18/11/22 (Noon) 18/11/22 Comprehensive cover Sections AB,C,D,E,FGJ in your Policy booklet are the "

re.search('18/11/21 \(Noor\) to',string).span()

Upvotes: 1

Related Questions