How to find the second number in a string with regex expression?

Member

by gilbert , in category: Third Party Scripts , 5 months ago

How to find the second number in a string with regex expression?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 5 months ago

@gilbert 

To find the second number in a string using a regex expression, you can use the following pattern:

1
d+D+(d+)


Explanation:

  • d+: Matches one or more digits
  • D+: Matches one or more non-digit characters
  • (d+): Matches and captures one or more digits (the second number)


Here's an example of how you can use this regex pattern in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import re

string = "The first number is 10 and the second number is 20"
match = re.search(r'd+D+(d+)', string)

if match:
    second_number = match.group(1)
    print("Second number: ", second_number)
else:
    print("Second number not found")


This code snippet will extract and print the second number (20 in this case) from the given string.

Related Threads:

How to find a regex pattern after a specific number of characters?
How to find repeated word in a string with regex?
How to find specific matches in a string using regex?
How to find a string at a specific location with regex with java?
How to get the second part of a hyphenated word using regex?
What is the maximum length of a regex expression?