Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - match returns None. Where am I wrong?

Tags:

python

regex

>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None

in Kiki that matches the test at the end of the s. What do I miss? (I tried re.compile(r'test$') as well)

like image 992
tetris555 Avatar asked Oct 22 '12 15:10

tetris555


People also ask

What does regex return if no match?

The match() function returns a match object if the text matches the pattern. Otherwise, it returns None . The re module also contains several other functions, and you will learn some of them later on in the tutorial.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.

What is \r and \n in regex?

Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.


1 Answers

Use

match1 = reg1.search(s)

instead. The match function only matches at the start of the string ... see the documentation here:

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

like image 169
Useless Avatar answered Oct 05 '22 17:10

Useless