Lumilens
Lumilens

Reputation: 1

Finding strings (including its special character) after keyword in python

Suppose I have a text that looks like this

text = No. ADJ.TRM/085/BFG/2015

the output that I wanted is ADJ.TRM/085/BFG/2015

I have tried using

re.search('(?<=No. )(\w+)',text)

It gives me only ADJ

also tried

re.search('No.\s\w+\s\w+\s(\w+)',text)

It gives me an error

Upvotes: 0

Views: 946

Answers (3)

user12842282
user12842282

Reputation:

\w is equivalent to [A-Za-z0-9_]

This excludes the . and the / that you are also trying to match.

While .* will work, if you're trying to be deliberate, then you can use a slight modification of your pattern to make it work:

>>> re.search('(?<=No. )([\w./]+)',text)
<re.Match object; span=(4, 24), match='ADJ.TRM/085/BFG/2015'>
>>>

[\w./] instead of \w is the same as [A-Za-z0-9_./]

Upvotes: 0

Eelco van Vliet
Eelco van Vliet

Reputation: 1238

if match := re.search("No\. (.*)", text):
    print(match.group(1))

Upvotes: 1

Adon Bilivit
Adon Bilivit

Reputation: 27073

It rather depends on the exact format of your string but, as given, you can simply do this:

text = 'No. ADJ.TRM/085/BFG/2015'

print(text.split()[1])

Output:

ADJ.TRM/085/BFG/2015

Upvotes: 0

Related Questions