How to dynamically extract numbers before text with regex?

Member

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

How to dynamically extract numbers before text with regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , a month ago

@kadin 

To dynamically extract numbers before text using regex, you can use a regular expression pattern that specifically captures numbers that occur before a certain text pattern. Here is an example of how you can do this in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import re

def extract_numbers_before_text(text, pattern):
    regex_pattern = r'(d+)(?=s*' + re.escape(pattern) + ')'
    match = re.search(regex_pattern, text)
    if match:
        return match.group(1)
    return ""

text = "The price is $25.99 for the item"
pattern = "dollars"
numbers_before_text = extract_numbers_before_text(text, pattern)

print(numbers_before_text)  # Output: 25


In this example, the extract_numbers_before_text function takes in a text string and a pattern for the text that comes after the numbers. The regex pattern r'(d+)(?=s*' + re.escape(pattern) + ') captures one or more digits d+ that are followed by the specified pattern using a positive lookahead (?=...). The re.search function is then used to find the first match of this pattern in the text.


You can modify the text and pattern variables to match your specific use case.