Last active
November 4, 2019 09:32
-
-
Save joe-oli/f6e0e4ab0928f02c9f1a2eb505017c1a to your computer and use it in GitHub Desktop.
Guid-validator-with-Regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Example #1 | |
------------ | |
Use | in a regular expression to match either what comes before or what comes after: | |
const re = /^([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})|[0-9]+$/i; | |
console.log('11111111-1111-1111-8111-111111111111'.match(re)[0]); | |
console.log('5555'.match(re)[0]); | |
Example #2 | |
------------ | |
another way is to OR the matches in an if statement: | |
var reg1 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; | |
var reg2 = /^[0-9]*$/; | |
var text = " ... "; | |
if (reg1.test(text) || reg2.test(text)) { | |
// do your stuff here | |
} | |
Another approach is ORing in the RegExp itself: | |
var regex = /(^[0-9]*)|^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; | |
var text = " ... "; | |
if (regex.test(text)) { | |
// do your stuff here | |
} | |
Example #3 | |
------------ | |
IsGuid() (Regular Expression Guid Match) | |
A regular expression for validating a string as being a Guid is.. | |
@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" | |
Example usage | |
Below is a function I try to keep handy which tests a string for a Guid and returns True or False. | |
public static bool IsGUID(string expression) | |
{ | |
if (expression != null) | |
{ | |
Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$"); | |
return guidRegEx.IsMatch(expression); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment