-1

Suppose, a = 'I was born in 1997'

And I want to print everything present in a using regular expression (just for learning purpose.)

So when I use: re.match(r'.*', a)

Then it shows match as: <_sre.SRE_Match object; span=(0, 18), match='I was born in 1997'>

But when I use: re.match(r'[.*]', a)

I get no output, i.e no match is found.

Pran Kumar Sarkar
  • 953
  • 12
  • 26

2 Answers2

1

. is a special character in regex which means match anything except new line.but when you use inside [] character class it becomes a normal character .

* is a quantifier which means zero or more time. but when you use in character class it becomes normal character *

  • .* ---> Means match anything except new line.

  • [.*] ---> means match . or *

For further reading

character class

Dot

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

The regular expression .* matches zero or more characters, so of course it matches the entire string.

The regular expression [.*] matches a single character that is either . or * (they lose their significance as meta-characters between square brackets). And since re.match matches only at the beginning of the string, it doesn't match anything. (re.search matches anywhere in the string, but it still wouldn't match anything in your string).

re.match(r'[AEIOU]', a) would match the I at the beginning of your string.

Documentation for Python regular expressions: https://docs.python.org/3.7/library/re.html

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631