正则表达式:检索[]括号内的GUID

tug*_*erk 6 javascript regex jquery

我需要在[ ]括号内获取GUID .这是一个示例文本:

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

我需要使用正则表达式使用JavaScript,但到目前为止,我失败了.知道如何检索这个值吗?

Dan*_*olm 15

以下正则表达式将匹配[8chars] - [4chars] - [4chars] - [4chars] - [12chars]格式中的GUID:

/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/i
Run Code Online (Sandbox Code Playgroud)

您可以使用以下函数在方括号内找到GUID:

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;
}
Run Code Online (Sandbox Code Playgroud)

请参阅运行示例:http://jsfiddle.net/Ng4UA/26/


dev*_*odo 5

这应该有效:

str.match(/\[([^\]]+)\]/)
Run Code Online (Sandbox Code Playgroud)

还有一个没有正则表达式的版本:

str.substring(str.indexOf('[') + 1, str.indexOf(']'))
Run Code Online (Sandbox Code Playgroud)

我会使用正则表达式,但使用第二个版本可能更方便。