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
  Regular Expression search to comment lines of code Gman2233 5 242 Sep-08-2022, 06:57 AM
Last Post: ndc85430
  Find and Replace numbers in String giddyhead 2 353 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 393 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  List Creation and Position of Continue Statement In Regular Expression Code new_coder_231013 3 585 Jun-15-2022, 12:00 PM
Last Post: new_coder_231013
  Need help with my code (regular expression) shailc 5 729 Apr-04-2022, 07:34 PM
Last Post: shailc
  Regular Expression for matching words xinyulon 1 1,144 Mar-09-2022, 10:34 PM
Last Post: snippsat
  Find if chain of characters or number Frankduc 4 838 Feb-11-2022, 01:55 PM
Last Post: Frankduc
Question Help to find the largest int number in a file directory SalzmannNicholas 1 694 Jan-13-2022, 05:22 PM
Last Post: ndc85430
  printing an string instead of a expression Underscore 2 1,065 Oct-11-2021, 03:10 PM
Last Post: deanhystad
  regular expression question Skaperen 4 1,485 Aug-23-2021, 06:01 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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