-3

I use python's re module to recognize integers in a sentence. It produces empty strings as well. Any idea on how to remove those empty strings?

In [15]: myre="[0-9]*"

In [16]: re.findall(myre,"23")
Out[16]: ['23', '']

In [17]: re.findall(myre,"23 is a good number.")
Out[17]:
['23',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '']
zell
  • 9,830
  • 10
  • 62
  • 115
  • 1
    This should answer your question: [Make regular expression not match empty string?](https://stackoverflow.com/questions/19620735/make-regular-expression-not-match-empty-string) – mkrieger1 Sep 18 '21 at 12:03

2 Answers2

2

You should be using [0-9]+ rather than [0-9]*; the latter matches against 0 or more (meaning that the digits are optional); +, however, matches against one or more.

saedx1
  • 984
  • 6
  • 20
1

The reason is your regex matches 0 or more occurences of digits. Change it to [0-9]+ or \d+ and try out.

Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16