1

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);
Filburt
  • 17,626
  • 12
  • 64
  • 115
Natali
  • 59
  • 6
  • Ive tried something like this:Regex urlRx = new Regex(@"^x-\[.*\]$", RegexOptions.IgnoreCase); – Natali Apr 06 '16 at 11:53
  • Your regex was perfect except you have to escape `[` and `]` because they have special meaning.. They are character class.. – rock321987 Apr 06 '16 at 12:02
  • See [*How to extract the contents of square brackets in a string of text in c# using Regex*](http://stackoverflow.com/questions/1811183/how-to-extract-the-contents-of-square-brackets-in-a-string-of-text-in-c-sharp-us). Easy to google. – Wiktor Stribiżew Apr 06 '16 at 12:26

3 Answers3

2

Simple:

x-\[([^]]+)\]
# that is: look for x-[ literally
# capture and save anything that is not a ]
# followed by ]

See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79
2

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);
}

IDEONE DEMO

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-\[([^\]]*)\]$
Community
  • 1
  • 1
rock321987
  • 10,942
  • 1
  • 30
  • 43
  • It is very inefficient to match everything (`.*`) and then backtrace - better be precise in the first place! – Jan Apr 06 '16 at 12:36
-1

Do you really need a regex for it? Simple String operation should serve your purpose.

yourString.EndsWith("]");
yourString.StartsWith("x-[");
SamGhatak
  • 1,487
  • 1
  • 16
  • 27
  • Its a big text and I need all the words that match this pattern – Natali Apr 06 '16 at 11:56
  • @Natali ok, then its better to use it..... for the downvote: if you need to perform these operation on a single string, string operations gives you better performance...refer [this](http://stackoverflow.com/questions/2962670/regex-ismatch-vs-string-contains) link......thats why i suggested this one – SamGhatak Apr 06 '16 at 13:01