1

enter image description hereI 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

5
  • Why exactly can't you use str.replace? Commented Mar 20, 2017 at 14:51
  • i have to use that index for further in non edited string .. If i will use str.replace it will not give correct index Commented Mar 20, 2017 at 14:52
  • You might want to try regular expressions that allow you to search for optional whitespace something like \(\w*B\w*\). Commented Mar 20, 2017 at 14:52
  • what will be the values inside the brackets? one letter? Commented Mar 20, 2017 at 14:53
  • @Nino no it may be one or more than one character and any number of white space may come Commented Mar 20, 2017 at 14:54

1 Answer 1

3

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*\)".

Sign up to request clarification or add additional context in comments.

3 Comments

Everything is fine but what if we want to search some string(it may be (A) or any other string foo) in other string str ?
@Ajeet: The current question does not really contain the requirements for what there must appear inside parentheses, that is why I suggested a rather generic pattern. The pattern can be adjusted more or less easily, but the requirements should be provided first.
So, you just need @"\([\sa-zA-Z]*\)", right? Whitespace or letter symbols only inside parentheses?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.