How To Use Regular Expressions To Find 2 Words With Any Number Of Spaces Between Them


Have youever wanted to find 2 words when parsing data, remove them, even though there may be a varying number of spaces between the words?



//set our test input string
string data = "what is   thought     is 1. the data is";   //our test string

//Now match on "is thought is" phrase with any number of SPACES between words
Match match = Regex.Match(data, "is\\s{1,}thought\\s{1,}is");

//Display if it was OK
Console.WriteLine("Success: " + match.Success);

//Display the index
Console.WriteLine("Index: " + match.Index);

//Display the length of the matched string
Console.WriteLine("Length: " + match.Length);

//Now grab everything AFTER the matched string
Console.WriteLine("Trimmed: " + data.Substring(match.Index +match.Length));




The output is:

Success: True
Index: 5
Length: 19
Trimmed:  1. the data is

Add comment

  Country flag

  • Comment
  • Preview