Reputation: 4397
I can have the following variants of a string
:
text
[text]
or [@text]
[OPTIONAL text]
or [OPTIONAL @text]
These are all possibilities. Is it possible via regular expression to easily extract the following information:
text
,[
and ]
,OPTIONAL
word,@
before text
?
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
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
Reputation: 463
This should do it for you:
regex = ([)?(\w+\s)?(\@)?(text)]?
This will capture everything you want....
[ OPTIONAL @ text
Good luck!
Upvotes: 0