Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression: Retrieve the GUID inside [ ] parenthesis

I need to get the GUID inside [ ] parenthesis. Here is a sample texts:

AccommPropertySearchModel.AccommPropertySearchRooms[6a2e6a9c-3533-4c43-8aa4-0b1efd23ba04].ADTCount

I need to do this with JavaScript using Regular Expressions but so far I am failing. Any idea how I can retrieve this value?

like image 808
tugberk Avatar asked Dec 03 '11 14:12

tugberk


2 Answers

The following regex will match a GUID in the [8chars]-[4chars]-[4chars]-[4chars]-[12chars] format:

/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/i

You could find a GUID within square brackets using the following function:

var re = /\[([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})\]/i;
function extractGuid(value) {    

    // the RegEx will match the first occurrence of the pattern
    var match = re.exec(value);

    // result is an array containing:
    // [0] the entire string that was matched by our RegEx
    // [1] the first (only) group within our match, specified by the
    // () within our pattern, which contains the GUID value

    return match ? match[1] : null;
}

See running example at: http://jsfiddle.net/Ng4UA/26/

like image 188
Dan Malcolm Avatar answered Oct 07 '22 16:10

Dan Malcolm


This should work:

str.match(/\[([^\]]+)\]/)

And a version with no regex:

str.substring(str.indexOf('[') + 1, str.indexOf(']'))

I would use the regex, but it may be more convenient for you to use the second version.

like image 44
deviousdodo Avatar answered Oct 07 '22 16:10

deviousdodo