Python Forum
Regular expression: cannot find 1st number in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regular expression: cannot find 1st number in a string
#1
Hello,

Here is test string:
aaa = '   2jhjh 890 jjk'
Here is how I try to find 1st number in aaa (2 in this case):
bbb = re.match('\d', aaa)
What I finally get:
Output:
>>> type(bbb) <class 'NoneType'>
Any suggestions ?

Thanks.
Reply
#2
Here is a solution using search:

bbb = re.search('\d', aaa).group()
So, match can't be used for this task ?
Reply
#3
Correct. Let's look at the description of match.

Quote:match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning
a Match object, or None if no match was found.

match() is as if your pattern has an implicit ^ anchoring to the beginning of the string. search() doesn't and can look elsewhere in the string.
ndc85430 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  printing an string instead of a expression Underscore 2 334 Oct-11-2021, 03:10 PM
Last Post: deanhystad
  regular expression question Skaperen 4 653 Aug-23-2021, 06:01 PM
Last Post: Skaperen
  How can I find all combinations with a regular expression? AlekseyPython 0 467 Jun-23-2021, 04:48 PM
Last Post: AlekseyPython
  Python Regular expression, small sample works but not on file Acernz 5 824 Jun-09-2021, 08:27 PM
Last Post: bowlofred
  Find string between two substrings, in a stream of data xbit 1 765 May-09-2021, 03:32 PM
Last Post: bowlofred
  TypeError: int() argument must be a string, a bytes-like object or a number, not 'Non Anldra12 2 1,710 May-02-2021, 03:45 PM
Last Post: Anldra12
  cursor.execute: How to insert dynamic number in a string? stoeberhai 2 1,083 Mar-18-2021, 12:55 PM
Last Post: stoeberhai
  Regular expression: return string, not list Pavel_47 3 913 Jan-14-2021, 11:49 AM
Last Post: Pavel_47
  Help with a regular expression t4keheart 2 788 Oct-13-2020, 04:05 PM
Last Post: t4keheart
  Please support regex for version number (digits and dots) from a string Tecuma 4 1,132 Aug-17-2020, 09:59 AM
Last Post: Tecuma

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020