Reputation: 31
I have string which contain white space like
string str="Option (A) and option ( B ) and (c )"
If and i want to search (A)
(B)
(C)
position and length I know I can use string.replace(" ","")
and search.
Here I know (B)
is there but due to white space I am not able to get correct Index and Length .
For example in this case I want str.IndexOf("(B)",0)
should return 22(I calculated manually). and also get length I mean my program should know here (B)
start index=22 and length=9 (here length of (B)
is not 3 because in string due to white space its increase to 9.
Thanks
Upvotes: 1
Views: 107
Reputation: 627537
Use a regex for this:
var str = "Option (A) and option ( B ) and (c )";
var matches = Regex.Matches(str, @"\([^()]*\)");
foreach (Match match in matches) {
Console.WriteLine("Value: {0}", match.Value);
Console.WriteLine("Position: {0}",match.Index);
Console.WriteLine("Length: {0}",match.Length);
}
See the C# demo
A Match
object has the necessary Index
and Length
properties you may access after getting all the matches.
The pattern here matches:
\(
- a literal (
[^()]*
- zero or more chars other than (
and )
\)
- a literal )
.You may adjust it say, to match (
, 0+ whitespaces, a letter, zero or more whitespaces and a )
by using @"\(\s*\p{L}\s*\)"
.
Upvotes: 3