Hippias Minor
Hippias Minor

Reputation: 1967

Regex to find special pattern

I have a string to parse. First I have to check if string contains special pattern:

  1. I wanted to know if there is substrings which starts with "$(", and end with ")",
  2. and between those start and end special strings,there should not be any white-empty space,
  3. it should not include "$" character inside it.

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

Answers (3)

Avinash Raj
Avinash Raj

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

Jerry
Jerry

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) and
  • abc and def in $(def)$()$(abc)(something).

Upvotes: 2

fnupp
fnupp

Reputation: 188

Simply replace the * with a + and merge the options.

string pattern = @"\$\(([^$\s]+)\)";

+ means 1 or more

* means 0 or more

Upvotes: 1

Related Questions