ebvtrnog
ebvtrnog

Reputation: 4397

Is it possible to write a regular expression to check for a few conditions

I can have the following variants of a string:

These are all possibilities. Is it possible via regular expression to easily extract the following information:

?

As for what I have done so far, I can

 var expressionMatch = Regex.Match(token, "[.*]");
 if (expressionMatch.Success)
 {
      // use now expressionMatch.Value;
      // check in the same way whether OPTIONAL word is there, etc.
 }

 // the input == text, all properties are false

But this is ugly. Is there a pretty / clean / simple way to do this?

Upvotes: 0

Views: 63

Answers (2)

Dour High Arch
Dour High Arch

Reputation: 21722

[.*] is not going to do what you want; [ and ] are regex metacharacter that enclose a character class; if you want to search for those characters you have to precede them with \. \[.*\] will require your strings to start with [ so your first example will not match. .* matches any character, including ] so you will have no way to determine whether your strings end with a ] or not.

As @jdweng suggested, you should use named groups to capture separate substrings in your pattern. The .NET syntax for named groups is (?<name>pattern). You seem to have five substrings in your pattern:

(?<leftBracket>\[?)(?<optional>(OPTIONAL )?)(?<at>\@?)(?<text>[^\]]+)(?<rightBracket>\]?)

If this pattern matches, expressionMatch.Groups["leftBracket"].Value will contain any left bracket or an empty string. For example, you can determine if the text is surrounded by brackets with:

!string.IsNullOrEmpty(expressionMatch.Groups["leftBracket"].Value)
    && !string.IsNullOrEmpty(expressionMatch.Groups["rightBracket"].Value)

The rest of the conditions are left as an exercise for the reader.

Upvotes: 1

AmericanMade
AmericanMade

Reputation: 463

This should do it for you:

regex = ([)?(\w+\s)?(\@)?(text)]?

This will capture everything you want....

[ OPTIONAL @ text

Good luck!

Upvotes: 0

Related Questions