How to match all words after a specific expressions with regex?

by dalton_moen , in category: Third Party Scripts , 2 days ago

How to match all words after a specific expressions with regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 2 days ago

@dalton_moen 

To match all words after a specific expression with regex, you can use a regular expression pattern with capturing groups. Here's an example:


Let's say you have the following text:


"Lorem ipsum dolor sit amet, consectetur adipiscing elit."


If you want to match all the words after the word "dolor", you can use the following regex pattern:

1
2
3
4
5
6
7
8
9
import re

text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
pattern = r"dolors+(.*)"
matches = re.search(pattern, text)

if matches:
    words_after_dolor = matches.group(1)
    print(words_after_dolor)


In this example, the regex pattern dolors+(.*) will match the word "dolor" followed by one or more whitespace characters, and then capture all the words after "dolor" into a group.


The matches.group(1) will then extract the words after "dolor" from the text.


You can adjust the regex pattern as needed to match different expressions and extract different parts of the text.