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



TODO:

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?

 

SOLUTION:

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

 

 

NOTES:

The output is:

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


Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading