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
  Convert any Python expression to a string voidtrance 2 1,130 Jun-23-2025, 07:06 AM
Last Post: DeaD_EyE
  Use or raw string on regular expressions Zaya_pool 5 3,737 May-09-2024, 06:10 PM
Last Post: Zaya_pool
  Regular expression help anilrajr 4 2,595 May-08-2024, 06:18 PM
Last Post: deanhystad
  data validation with specific regular expression shaheen07 0 1,265 Jan-12-2024, 07:56 AM
Last Post: shaheen07
  find the sum of a series of values that equal a number ancorte 1 1,734 Oct-30-2023, 05:41 AM
Last Post: Gribouillis
Question Extracting Version Number from a String britesc 2 4,326 May-31-2023, 10:20 AM
Last Post: britesc
  find random numbers that are = to the first 2 number of a list. Frankduc 23 10,021 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Regular Expression search to comment lines of code Gman2233 5 3,858 Sep-08-2022, 06:57 AM
Last Post: ndc85430
  Find and Replace numbers in String giddyhead 2 4,943 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 7,897 Jul-01-2022, 01:23 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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