Reputation: 1967
I have a string to parse. First I have to check if string contains special pattern:
I have a little regex for it in C#
string input = "$(abc)";
string pattern = @"\$\(([^$][^\s]*)\)";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
foreach (var match in matches)
{
Console.WriteLine("value = " + match);
}
It works for many cases but failed at input= $(a$() , which inside the expression is empty. I wanted NOT to match when input is $().[ there is nothing between start and end identifiers].
What is wrong with my regex?
Upvotes: 1
Views: 108
Reputation: 174696
Note: [^$]
matches a single character but not of $
Use the below regex if you want to match $()
\$\(([^\s$]*)\)
Use the below regex if you don't want to match $()
,
\$\(([^\s$]+)\)
*
repeats the preceding token zero or more times.+
Repeats the preceding token one or more times.Your regex \(([^$][^\s]*)\)
is wrong. It won't allow $
as a first character inside ()
but it allows it as second or third ,, etc. See the demo here. You need to combine the negated classes in your regex inorder to match any character not of a space or $
.
Upvotes: 3
Reputation: 71538
Your current regex does not match $()
because the [^$]
matches at least 1 character. The only way I can think of where you would have this match would be when you have an input containing more than one parens, like:
$()(something)
In those cases, you will also need to exclude at least the closing paren:
string pattern = @"\$\(([^$\s)]+)\)";
The above matches for example:
abc
in $(abc)
andabc
and def
in $(def)$()$(abc)(something)
.Upvotes: 2
Reputation: 188
Simply replace the * with a + and merge the options.
string pattern = @"\$\(([^$\s]+)\)";
+ means 1 or more
* means 0 or more
Upvotes: 1