Get Strings Between Characters in Brackets in C#

How to extract all strings between brackets using c#?

Here is a LINQ solution:

var result = myString.Split().Where(x => x.StartsWith("(") && x.EndsWith(")")).ToList();

Values stored in result:

result[0] = (1)
result[1] = (0000000000)

And if you want only the numbers without the brackets use:

var result = myString.Split().Where(x => x.StartsWith("(") && x.EndsWith(")"))
.Select(x=>x.Replace("(", string.Empty).Replace(")", string.Empty))
.ToList();

Values stored in result:

result[0] = 1
result[1] = 0000000000

Get Strings Between Characters in Brackets in C#

You can use regex or with this simple string pure string methods. First find the beginning and the end of the brackets with String.IndexOf. Then use Substring and Split:

static string[] ExtractArguments(string methodSig)
{
int bracketStart = methodSig.IndexOf('(');
if (bracketStart == -1) return null;
int bracketEnd = methodSig.IndexOf(')', bracketStart + 1);
if (bracketEnd == -1) return null;
string arguments = methodSig.Substring(++bracketStart, bracketEnd - bracketStart);
return arguments.Split(',').Select(s => s.Trim()).ToArray();
}

Regex to extract string between parentheses which also contains other parentheses

You can change exception for @ symbol in your regex to regex matches any characters and add quantifier that matches from 0 to infinity symbols. And also simplify your regex by deleting group construction:

\(.*\)

Here is the explanation for the regular expression:

  • Symbol \( matches the character ( literally.
  • .* matches any character (except for line terminators)
  • * quantifier matches between zero and unlimited times, as many times
    as possible, giving back as needed (greedy)
  • \) matches the character ) literally.

You can use regex101 to compose and debug your regular expressions.

C# get text between brackets

Use Regex.Matches method:

For example:

String text = "faces=rect64(3f845bcb59418507),8e62398ebda8c1a5;rect64(9eb15e89b6b584c1),d10a8325c557b085";
Regex re = new Regex(@"rect64\(([a-f0-9]+)\)");
foreach (Match match in re.Matches(text)) {
Console.WriteLine(match.Groups[1]); // print the captured group 1
}

See a demo: http://ideone.com/Oayuo5

How do I extract text that lies between brackets in special order?

You will need balancing groups. This is not an exact duplicate but the regex there can be used to solve your problem. First the basic regex:

\[(?:[^\[\]]|(?<o>\[)|(?<-o>\]))+(?(o)(?!))\]

\[            # Match an opening square bracket
(?: # Group begin
[^\[\]] # Match non-square brackets
| # Or
(?<o>\[) # An opening square bracket which we name 'o'.
| # Or
(?<-o>\]) # A closing square bracket and we remove an earlier square bracket
)+ # Repeat the group as many times as possible
(?(o)(?!)) # Fail if a group named 'o' exists at this point
\] # Match the final closing square bracket

Then to get the inner matches, you can use a lookahead and a capture group so you can get overlapping matches:

(?=(\[(?:[^\[\]]|(?<o>\[)|(?<-o>\]))+(?(o)(?!))\]))

ideone demo

How to remove text between multiple pairs of brackets?

You have two main possibilities:

  • change .* to .*? i.e. match as few as possible and thus match ) as early as possible:

    text = Regex.Replace(text, @"\(.*?\)", "");
    text = Regex.Replace(text, @"\s{2,}", " "); // let's exclude trivial replaces
  • change .* to [^)]* i.e. match any symbols except ):

    text = Regex.Replace(text, @"\([^)]*\)", "");
    text = Regex.Replace(text, @"\s{2,}", " ");

How to get text between nested parentheses?

.NET allows recursion in regular expressions. See Balancing Group Definitions

var input = @"add(mul(a,add(b,c)),d) + e - sub(f,g)";

var regex = new Regex(@"
\( # Match (
(
[^()]+ # all chars except ()
| (?<Level>\() # or if ( then Level += 1
| (?<-Level>\)) # or if ) then Level -= 1
)+ # Repeat (to go from inside to outside)
(?(Level)(?!)) # zero-width negative lookahead assertion
\) # Match )",
RegexOptions.IgnorePatternWhitespace);

foreach (Match c in regex.Matches(input))
{
Console.WriteLine(c.Value.Trim('(', ')'));
}


Related Topics



Leave a reply



Submit