Regex to extract first 3 words from a string

前端 未结 3 1696

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.

3条回答
  •  不思量自难忘°
    2020-12-11 11:02

    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);
    

提交回复
热议问题