Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching words after a word

I'm wondering, is it possible to use regex to match a word after a specific word? For example, suppose you have a string like this:

test abcde  
dummy test fghij

Would it be possible to obtain a string array which contains the words after test (abcde and fghij)? If so, can you explain?

like image 816
rayanisran Avatar asked Feb 03 '26 12:02

rayanisran


2 Answers

Here is my suggestion for you:

(?:test\s)(?<word>\b\S+\b)

Explanation

(?:test\s)       matches "test" with a trailing blank, but does not include it in the capture
(?<word>\b\S+\b) matches a word with any character except a whitespace. It will be stored in a group called "word".

Here is a little example how to use it:

var regex = new Regex(@"(?:test\s)(?<word>\b\S+\b)");
var matchCollection = regex.Matches("test abcde   dummy test fghij ");

foreach (Match match in matchCollection)
{
    Debug.WriteLine(match.Groups["word"].Value);
}
like image 123
Fischermaen Avatar answered Feb 06 '26 00:02

Fischermaen


Do not use RegEx, but a simple yourString.Split(' ');.

Then, you can :

var strings = yourString.Split(' ');

var afterTest = strings.Skip(strings.IndexOf("test"))

It will be faster, simpler and more secure.

Also read Jeff Atwood's entry about regex

like image 33
Steve B Avatar answered Feb 06 '26 00:02

Steve B