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
  data validation with specific regular expression shaheen07 0 328 Jan-12-2024, 07:56 AM
Last Post: shaheen07
  find the sum of a series of values that equal a number ancorte 1 493 Oct-30-2023, 05:41 AM
Last Post: Gribouillis
Question Extracting Version Number from a String britesc 2 1,087 May-31-2023, 10:20 AM
Last Post: britesc
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,198 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Regular Expression search to comment lines of code Gman2233 5 1,659 Sep-08-2022, 06:57 AM
Last Post: ndc85430
  Find and Replace numbers in String giddyhead 2 1,221 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 4,849 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  List Creation and Position of Continue Statement In Regular Expression Code new_coder_231013 3 1,661 Jun-15-2022, 12:00 PM
Last Post: new_coder_231013
  Need help with my code (regular expression) shailc 5 1,917 Apr-04-2022, 07:34 PM
Last Post: shailc
  Regular Expression for matching words xinyulon 1 2,164 Mar-09-2022, 10:34 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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