C# Regex for Guid

C# Regex for Guid

This one is quite simple and does not require a delegate as you say.

resultString = Regex.Replace(subjectString, 
@"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$",
"'$0'");

This matches the following styles, which are all equivalent and acceptable formats for a GUID.

ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)

Update 1

@NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter.

This can be avoided by regex conditionals which are broadly supported.

Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework.
Ruby supports them starting with version 2.0. Languages such as Delphi, PHP, and R that
have regex features based on PCRE also support conditionals. (source http://www.regular-expressions.info/conditional.html)

The regex that follows Will match

{123}
(123)
123

And will not match

{123)
(123}
{123
(123
123}
123)

Regex:

^({)?(\()?\d+(?(1)})(?(2)\))$

The solutions is simplified to match only numbers to show in a more clear way what is required if needed.

Regular Expression to identify a Guid followed by a number

You can use the following regex:

\b[\dA-F]{8}-[\dA-F]{4}-[\dA-F]{4}-[\dA-F]{4}-[\dA-F]{12}-\d+

Regular expression visualization

Demo

string input = "id=1 name=4a3779ab-56cc-41b5-ac7c-03bbf673439c-53607.jpg count=53607";
Match m = Regex.Match(input, @"\b[\dA-F]{8}-[\dA-F]{4}-[\dA-F]{4}-[\dA-F]{4}-[\dA-F]{12}-\d+", RegexOptions.IgnoreCase);
string output = null;
if (m.Success)
output = m.Value;

Regular expression to find GUID and numbers in range

There is no language specified, but you might also use a broader match with 2 capturing groups where each of the match for a number starts at 1, and using code you could check if the values from the group are lower or equal than 65536.

^[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}:([1-9][0-9]*):([1-9][0-9]*)$

Explanation

  • ^ Start of string
  • [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} Match the guid format
  • :([1-9][0-9]*) Match : and capture group 1 to match a number starting from 1
  • :([1-9][0-9]*) Match : and capture group 2 to match a number starting from 1
  • $ End of string

For example using C# (It is listed as your top tag)

string pattern = @"^[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}:([1-9][0-9]*):([1-9][0-9]*)$";
string s = @"123e4567-e89b-12d3-a456-9AC7CBDCEE52:21:4552";
int n1;
int n2;

Match m = Regex.Match(s, pattern);

if (m.Success && Int32.TryParse(m.Groups[1].Value, out n1) && Int32.TryParse(m.Groups[1].Value, out n2)) {
if (n1 <= 65536 && n2 <= 65536) {
Console.WriteLine("Match");
}
}

Output

Match

Surround a GUID with single quotes in C# using Regex

You may match a GUID inside single quotes and capture it to be able to test this group for a match inside a match evaluator, and match a GUID in all other contexts that will be enclosed with single quotes:

var inputString = @"ObjectID='{A591C480-2979-48ED-9796-5C3149472E7A}' and ObjectID={90f0fb85-0f80-4466-9b8c-2025949e2079}";
var guid = @"[({]?\s?[a-zA-Z0-9]{8}\s?[-]?\s?(?:[a-zA-Z0-9]{4}\s?[-]?\s?){3}\s?[a-zA-Z0-9]{12}\s?[})]?";
inputString = Regex.Replace(inputString, $@"('{guid}')|{guid}", x =>
x.Groups[1].Success ? x.Value : $"'{x.Value}'");
Console.WriteLine(inputString);
// => ObjectID='{A591C480-2979-48ED-9796-5C3149472E7A}' and ObjectID='{90f0fb85-0f80-4466-9b8c-2025949e2079}'

See the C# demo.

Note I made the ([a-zA-Z0-9]{4}\s?[-]?\s?) capturing group in the original pattern non-capturing, (?:[a-zA-Z0-9]{4}\s?[-]?\s?).

The $@"('{guid}')|{guid}" string literal creates a regex like

('[({]?\s?[a-zA-Z0-9]{8}\s?[-]?\s?(?:[a-zA-Z0-9]{4}\s?[-]?\s?){3}\s?[a-zA-Z0-9]{12}\s?[})]?')|[({]?\s?[a-zA-Z0-9]{8}\s?[-]?\s?(?:[a-zA-Z0-9]{4}\s?[-]?\s?){3}\s?[a-zA-Z0-9]{12}\s?[})]?

The first alternative matches and captures a GUID inside single quotes into Group 1 and the second alternative matches GUIDs in other contexts. The x => x.Groups[1].Success ? x.Value : $"'{x.Value}'" line only wraps the match with 's if it was not already enclosed with single quotes.

Find matching guid in string

If you would like to get the GUID using a Regex pattern. Then, try this pattern

(\{){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

string findGuid = "hi sdkfj 1481de3f-281e-9902-f98b-31e9e422431f sdfsf 1481de3f-281e-9902-f98b-31e9e422431f"; //Initialize a new string value
MatchCollection guids = Regex.Matches(findGuid, @"(\{){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}"); //Match all substrings in findGuid
for (int i = 0; i < guids.Count; i++)
{
string Match = guids[i].Value; //Set Match to the value from the match
MessageBox.Show(Match); //Show the value in a messagebox (Not required)
}

Regex Matcher matching TWO GUIDs from a string

Notice: I've used the same pattern you've provided but simply removed the ^ character which indicates that the expression must match from the start of the string. Then, removed the $ character which indicates that the expression must match from the end of the string.

More information about Regular Expressions can be found here:

Regular Expressions - a Simple User Guide and Tutorial

Thanks,

I hope you find this helpful :)

Regex: Find Guid (with/without dashes and with/without delimeters) in a long string

From Wikipedia:

In its canonical textual representation, the sixteen octets of a UUID
are represented as 32 hexadecimal (base 16) digits, displayed in five
groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36
characters

Then regex would be:

{?\w{8}-?\w{4}-?\w{4}-?\w{4}-?\w{12}}?

Live demo

Regular Expression to find a GUID string in a txt file with id= attached to it

You can use the following code to replace your corresponding code line:

MatchCollection guids = Regex.Matches(s, @"id=""\{?[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}}?""");

In C# verbatim string literals (see Point 2 at this link), that look like @"...", a literal quotation mark must be doubled.

The {0,1} limiting quantifier can be safely changed into ? (1 or 0 occurrences).

The - char outside of character classes (not inside [...] construct) do not have to be escaped.

See the regex demo.

Extract GUID from line in C#

Yes, you can. Cause you return only the first match of regex, you can use Regex.Match instead of Regex.Matches.

private static string RetrieveGUID2(string[] lines)
{
foreach (var line in lines)
{
var match = Regex.Match(line, @"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?");
if (match.Success)
return match.Value;
}

return null;
}

Extract a GUID from a string. How can I do it?

Try something like this Example , if every input follows the same patter like Board-:

string complexGuid = "Board-f330c10a-a9eb-4253-b554-43ed95c87242";
string extractedGuid = complexGuid.Substring(complexGuid.IndexOf('-') +1 );

Here complexGuid.IndexOf('-') will return the first index of the '-' which is the - after the Board in the given example. we need to skip that also so add a +1 so that .Substring() will give you the expected output for you.

Parse guid by Regular Expressions with slashes ('/') in C#

You can do that without Regex, Split on / and then use Guid.TryParse the last element, or all the elements like:

string str = "/string1/string2/f63112f7-caae-38f4-9655-e23d6b530315";
Guid tempGuid;
foreach (var item in str.Split('/'))
{
if (Guid.TryParse(item, out tempGuid))
{
Console.WriteLine(item);
break;
}
}

If you are always expecting the Guid to at the end of string then instead of looping through all elements, just access the last element from the split array and use that in Guid.TryParse

if(Guid.TryParse(str.Split('/').LastOrDefault(), out tempGuid))
{
//found Guid at the end of string
}


Related Topics



Leave a reply



Submit