1

I'm trying to create a regex expression what will accept a certain format of command. The pattern is as follows:

Can start with a $ and have two following value 0-9,A-F,a-f (ie: $00 - $FF) or Can be any value except for "&<>'/"

*if the value start with $ the next two values after need to be a valid hex value from 00-ff

So far I have this

Regex correctValue = new Regex("($[0-9a-fA-F][0-9a-fA-F])");

Any help will be greatly appreciated!

1
  • I don't understand this part of your question: Can be any value except for "&<>'/". Do you mean it should match any single character that's not in that list? Commented Aug 1, 2012 at 1:02

3 Answers 3

3

You just need to add "\" symbol before your "$" and it works:

        string input = "$00";

        Match m = Regex.Match(input, @"^\$[0-9a-fA-F][0-9a-fA-F]$");
        if (m.Success)
        {
            foreach (Group g in m.Groups)
                Console.WriteLine(g.Value);
        }
        else
            Console.WriteLine("Didn't match");
Sign up to request clarification or add additional context in comments.

1 Comment

Well, I also added ^ and $ to mark the beginning and the ending of the regex
2

If I'm following you correctly, the net result you're looking for is any value that is not in the list "&<>'/", since any combination of $ and two alphanumeric characters would also not be in that list. Thus you could make your expression:

Regex correctValue = new Regex("[^&<>'/]");

Update: But just in case you do need to know how to properly match the $00 - $FF, this would do the trick:

Regex correctValue = new Regex("\$[0-9A-Fa-f]{2}");

Comments

2

In Regular Expression $ use for Anchor assertion, and means:

The match must occur at the end of the string or before \n at the end of the line or string.

try using [$] (Character Class for single character) or \$ (Character Escape) instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.