Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract first 3 words from a string

Tags:

regex

I am trying to replace all the words except the first 3 words from the String (using textpad).

Ex value: This is the string for testing.

I want to extract just 3 words: This is the from above string and remove all other words.

I figured out the regex to match the 3 words (\w+\s+){3} but I need to match all other words except the first 3 words and remove other words. Can someone help me with it?

like image 656
user3234151 Avatar asked Jan 25 '14 02:01

user3234151


1 Answers

Exactly how depends on the flavor, but to eliminate everything except the first three words, you can use:

^((?:\S+\s+){2}\S+).*

which captures the first three words into capturing group 1, as well as the rest of the string. For your replace string, you use a reference to capturing group 1. In C# it might look like:

resultString = Regex.Replace(subjectString, @"^((?:\S+\s+){2}\S+).*", "${1}", RegexOptions.Multiline);
like image 50
Ron Rosenfeld Avatar answered Nov 30 '22 01:11

Ron Rosenfeld