Dan Mooray
Dan Mooray

Reputation: 245

How do I prevent superfluous newlines from appearing in my regex matches?

I have the folowing string

'TOKEN a$dmin\r\n'

And I would like to extract the value 'a$dmin' from it. I'm using

re.findall("(?i)TOKEN (.*)",string)

but what I'm getting is 'a$dmin\r\n'

How do I do this correctly?

Upvotes: 1

Views: 156

Answers (1)

georg
georg

Reputation: 214949

Either match against str.strip:

re.findall(r"(?i)TOKEN (\S*)", s.strip())

or change the expression to match only non-spaces:

re.findall(r"(?i)TOKEN (\S*)", s)

In case you have literal slashes, as in:

s = r'TOKEN a$dmin\r\n'

use this expression to match everything before the first slash:

re.findall(r"(?i)TOKEN (.*?)\\", s)

Upvotes: 6

Related Questions