Hi, i am looking for a regex pattern that will return me the contents of the first set of brackets in a string.
Eg - text text text text (hello) text (hello2) (hello3) text
..will return "hello"
does anyone know what the pattern looks like for c#?
Hi, i am looking for a regex pattern that will return me the contents of the first set of brackets in a string.
Eg - text text text text (hello) text (hello2) (hello3) text
..will return "hello"
does anyone know what the pattern looks like for c#?
The regexp pattern would look something like this:
\(([^)]*)\)
Pattern autopsy:
\( - a literal "("
( - start of subpattern:
[^)]* match 0 or more characters which are not ")" - note: we're defining a character group, so we don't have to escape the ) character here.
) - end of subpattern
\) - a literal ")"
The full pattern will match the brackets and the text inside them, the first subpattern will match only the text inside the brackets (see C# reference how to get them - I don't speak C# ;))
Bare regex:
\((.*?)\)
In Python you can use it this way:
import re
rx = re.compile(r'\((.*?)\)')
s = 'text text text text (hello) text (hello2) (hello3) text'
rxx = rx.search(s)
if rxx:
print(rxx.group(1))
If the strings are relatively small, you could use a replace instead of a match:
string s = Regex.Replace("text text text text (hello) text (hello2) (hello3) text", @"^.*?\(([^)]*)\).*$", "$1");
This will return you only what is within the first set of brackets:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Match match = Regex.Match("foo bar (first) foo bar (second) foo", @"\((.*?)\)");
if (match.Groups.Count > 1)
{
string value = match.Groups[1].Value;
System.Console.WriteLine(value);
}
}
}
}