roryhewitt
roryhewitt

Reputation: 4507

How can I check for specific strings in python?

I'm used to doing Regex's in a variety of languages, but I don't know Python well.

I'm looking for a regex that will do the same as the following JavaScript regex:

(disc|dis|se|oti)(\d+)\W

i.e. where the string will consist of one of those 4 strings followed by one or more digits followed by a space. This string will appear at the very beginning of the string (so I can use re.match rather than re.search).

It looks like I can use this:

re.match( r'(disc|dis|se|oti)(\d+)\s', line)

but should I be using the 'r' at the beginning?

Upvotes: 0

Views: 57

Answers (2)

Teja
Teja

Reputation: 141

http://docs.python.org/2/library/re.html

Will help you understand about regex in python2.7

Upvotes: 0

Ypnypn
Ypnypn

Reputation: 931

The r in the string means that the backslashes \ in the string won't create unusual characters, so it's usually a good idea.

Also note you need to import re at the beginning of the program.

Full code

import re
match = re.match( r'(disc|dis|se|oti)(\d+)\s', line)

or omit the r before the string, and double all the backslashes:

import re
match = re.match( '(disc|dis|se|oti)(\\d+)\\s', line)

Upvotes: 2

Related Questions