What is the Regular Expression in C# to find matches inside text that starting with "x-[" and ending with "]"?
I've tried something like this:
Regex urlRx = new Regex(@"^x-[.*]$", RegexOptions.IgnoreCase);
What is the Regular Expression in C# to find matches inside text that starting with "x-[" and ending with "]"?
I've tried something like this:
Regex urlRx = new Regex(@"^x-[.*]$", RegexOptions.IgnoreCase);
Simple:
x-\[([^]]+)\]
# that is: look for x-[ literally
# capture and save anything that is not a ]
# followed by ]
This should work
string input = "x-[ABCD]";
string pattern = "^x-\\[(.*)\\]$";
Regex rgx = new Regex(pattern);
Match match = rgx.Match(input);
if (match.Success) {
Console.WriteLine(match.Groups[1].Value);
}
UPDATE
As pointed by Jan, there will be too much backtracking in cases like x-[ABCDEFGHJJHGHGFGHGFVFGHGFGHGFGHGGHGGHGDCNJK]ABCD]
. My updated regex
is similar to his
^x-\[([^\]]*)\]$
Do you really need a regex for it? Simple String
operation should serve your purpose.
yourString.EndsWith("]");
yourString.StartsWith("x-[");