Understanding re.search () behavior in Python

Here is the python code I used to separate the letters and numbers from the string of alphanumerics:

input_string = 'abcdefghijklmnopqrstuvwxyz1234567890'
import re
print re.search('[a-z]*', input_string).group()
print re.search('[0-9]*', input_string).group()

In the outputs, I get a string with letters, but I don't get a string of numbers. If I change the code as shown in the following output, the numbers are:

print re.search('[0-9]*$', input_string).group()

I use grep, and I found that its functionality is similar to the functions of the module re, if I run the following command in the shell, I get the desired result:

echo "abcdefghijklmnopqrstuvwxyz1234567890" | grep "[0-9]*"

Am I missing something?

+4
source share
2 answers

I suggest you use a re.findallfunction (to perform a global match) instead re.search, because it re.searchwill only return the first match.

>>> input_string = 'abcdefghijklmnopqrstuvwxyz1234567890'
>>> print re.findall(r'\d+|[a-z]+', input_string)
['abcdefghijklmnopqrstuvwxyz', '1234567890']

[a-z]*, . * , + .

>>> print re.search(r'\d+', input_string).group()
1234567890
>>> print re.search(r'[a-z]+', input_string).group()
abcdefghijklmnopqrstuvwxyz

, ?

>>> print re.search('[a-z]*', input_string).group()
abcdefghijklmnopqrstuvwxyz
>>> print re.search('[0-9]*', input_string).group()

>>>

* , .. , . [a-z]* abcdefghijklmnopqrstuvwxyz, . 8abcdefghijklmnopqrstuvwxyz, . - re.search, . 8 , , [a-z]* regex , 8.

regex = [0-9]*, string = "abcdefghijklmnopqrstuvwxyz1234567890"

re.search . a [0-9], [0-9]* , a, * . .

>>> print re.search('[0-9]*$', input_string).group()
1234567890

, . , .

>>> print re.search('[0-9]*$', '12foo').group()

>>> 
+6

, .

ruby, perl, .

digit pattern :

  • , .
  • , .
  • .
  • .

re.search() .

letter pattern :

  • .
  • 1 2.
  • 2 3.
  • .

, :

echo "abcdefghijklmnopqrstuvwxyz1234567890" | grep "[0-9]*"

bash :

$ echo "abcdefghijklmnopqrstuvwxyz1234567890" | grep "[0-9]*"
abcdefghijk

, grep .

:

$ bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin10.0)
Copyright (C) 2007 Free Software Foundation, Inc.

$ echo "abc123" | grep -o "[a-z]*"
abc
$ echo "abc123" | grep -o "[0-9]*"
$ echo "abc123" | grep -o "[0-9]*$"
123
$ 
+1

All Articles