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

Member

by gilbert , in category: Third Party Scripts , a month ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , a month 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.