1

Below is a code I am trying out (to learn regex myself).

a = "This island is beautiful"
reg = re.compile(r'\bis\b')
print(reg.match(a))
print(reg.findall(a))
print(reg.search(a).group(0))

The output of the code is

None
['is']
is

As you can see, findall & search found the word 'is' in the string but match returns None.

Shouldn't match also find the word 'is'? I am confused.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
moys
  • 7,747
  • 2
  • 11
  • 42
  • 1
    Yes, but `re.match` matches *only* at the start of a string. You want `re.search` instead. – mechanical_meat Feb 11 '20 at 04:28
  • 1
    `match(str[,pos[,endpos]])` looks at `pos` which defaults to 0 in string for start of `str` and can't match it so gives `None`. `print(reg.match(a,12))` should work. – Ramesh Kamath Feb 11 '20 at 04:38

1 Answers1

0

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

https://docs.python.org/3/library/re.html#search-vs-match

jarthur
  • 393
  • 1
  • 2
  • 18