开发者

comparing string in C# vs a static Regex?

I was wondering, is there any easy way for those who are really unfamiliar with regex to find out how to match a string with the regex format for the specified string?

For example, this string, which is generated from another function i have:

3A5AE0F4-EB22-434E-80C2-273E315CD1B0

I have no clue what so ever what the proper 开发者_运维知识库regex for this string is.

Lets say i had a function taking this string as a parameter

        public static bool isValidRegex(string inputString)
        {
            Regex myRegex = ????

            if inputstring matches myRegex then
            return true;

            else 
            return false;


        }

What would the Regex be to make this function return true?

NOTE: As i am unfamiliar with C# the code provided may not be correct at all, and i am aware.


In this case, it looks like this is a Guid - if you're using .NET 4, the simplest approach is probably to use Guid.TryParse... but if you need to use a regex, it would probably be:

^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$

In other words, start of string, 8 hex digits, dash, 4 hex digits, dash, 4 hex digits, dash, 4 hex digits, dash, 12 hex digits, end of string. Note that I've assumed any alphabetic characters will be upper case rather than lower.

It's probably worth creating this just once, and possibly compiling it, so you'd end up with:

private static readonly Regex GuidPattern = new Regex
    ("^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$",
      RegexOptions.Compiled);

public static bool IsValidRegex(string inputString)
{
    return GuidPattern.IsMatch(inputString);
}


if the format is 8 letters - 4 - 4 - 4 - 12

then it is

[0-9A-Z]{8}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{12}


Something like that:

^[0-9A-Z]{8}-[0-9A-Z]{4}[0-9A-Z]{4}[0-9A-Z]{4}[0-9A-Z]{12}$

Between the curly braces you have the number of the elements, and between the [] you have all possible numbers an letters.


Regex is a way of matching an exact value to a pattern. But you need to know what sort of pattern you will accept. In the example you quote what provides an acceptable match?

"3A5AE0F4-EB22-434E-80C2-273E315CD1B0" is the exact value

Would you be happy if someone passsed in "3A5AE0F4-EB22-434E-80C2-273E315CD1B1" or "xxxxxxxx-EB22-434E-80C2-273E315CD1B0"

or "xxx"

or 3.14257

etc.

So that's the first thing and it's determined by your requirements which you haven't made clear.

Then

 string sPattern = "^[a-zA-Z0-9]+$";
 bool match = Regex.IsMatch(yourstring, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)

will return true if your string contains only alphanumeric characters

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜