I have string like
string = "TESt|SomethingTo||Search";
Need to find out match of searchstring ="test|"
. Please let me know how to get the result.
I have used below code
retval = new NSMutableAttributedString(str);
var matches = Regex.Matches(retval.Value, searchStr, RegexOptions.IgnoreCase);
But in matches it is not returning the 'test|'
, it returns only 'test'
.
How to handle this ? Same thing happens while using '*'.
CodePudding user response:
you can use the below regex expression to match the "test|" values.'(test\| )'
CodePudding user response:
The reason it happens both with the |
and *
characters is that those characters (and some others) are reserved in Regular Expressions, they mean something, and you have to escape them if you do not want the regular expression to interpret them.
The escaping character is \
so adding that character before the reserved one does the trick. For example:
string textToMatch ="test|";
string escapedText = Regex.Escape(textToMatch); // escapedText contains "test\|"
You can either escape those characters manually or use the Regex.Escape() function. That function is usefull if you do not know if the string to match will contain reserved characters. For exampe if it is user input.
string searchStr = @"(test\|)";
var matches = Regex.Matches(retval.Value, searchStr, RegexOptions.IgnoreCase);
You could also need the user to enter the matching expression, and to avoid error you should escape it:
Console.WriteLine("Enter the matching string");
string userInput = Console.ReadLine();
string searchStr = Regex.Escape(userInput); // This would avoid errors because there characters would be escaped.
var matches = Regex.Matches(retval.Value, "(" searchStr ")", RegexOptions.IgnoreCase);