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

8
我需要获取方括号中的GUID。以下是示例文本:
AccommPropertySearchModel.AccommPropertySearchRooms[6a2e6a9c-3533-4c43-8aa4-0b1efd23ba04].ADTCount
我需要使用正则表达式在JavaScript中完成此操作,但目前失败了。有什么想法可以检索此值吗?
5个回答

18

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

```regex ^[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}$ ```
/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/i

使用下面的函数可以在方括号内找到 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;
}

请查看示例运行结果:http://jsfiddle.net/Ng4UA/26/


[a-e0-9]会更加严格,以匹配GUID。 - monish001
@Monish 确定是[a-f0-9]吗?我已经更新了我的回答。 - Dan Malcolm

5
这应该可以正常工作:
str.match(/\[([^\]]+)\]/)

同时还有一个不包含正则表达式的版本:

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

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


谢谢!它起作用了,但是也检索了带有GUID的第一个[ - tugberk
我明白了。所以,它会返回一个数组对象。我可以使用这段代码检索出纯GUID:str.match(/\[([^\]]+)\]/)[1] - tugberk
这对我来说很有效。有点跑题,但是 match 方法总是返回数组对象还是取决于正则表达式? - tugberk
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/5553/discussion-between-tugberk-and-draevor - tugberk
1
如果String.match匹配到了某些内容,它将始终返回一个数组,否则将返回null。只有数组结构取决于正则表达式。 - deviousdodo
显示剩余3条评论

4

这对我来说是有效的,使用了测试GUID。

var guid = '530d6596-56c2-4de7-aa53-76b9426bdadc'; // sample GUID
var regex = /^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$/i; // validate 8-4-4-4-12
var addDate = function() {
        var newDate = new Date();
        var setGUIDtime = newDate.toString();
        return setGUIDtime;
}; // add date
console.log(guid.match(regex) + ', ' + addDate()); //display/print true GUID with date

1
var testString = "AccommPropertySearchModel.AccommPropertySearchRooms[6a2e6a9c-3533-4c43-8aa4-0b1efd23ba04].ADTCount";
var regex = /\[([a-z0-9\-]+)\]/i;
document.write(testString + "<br/><br/>");
document.write(regex.exec(testString)[1]);

regex.exec(testString)[1] 就是魔法的发生地。

exec 方法返回一个数组,其中包含找到的分组,索引0是整个匹配,1是第一个分组(分组由括号定义)。


0

这应该可以工作

(?<=\[).*?(?=\])

糟糕,Javascript不支持向后查找

因此,请使用 (\[).*?(\]) 并删除前导和尾随字符。

或者

只需使用 (\[)(.*?)(\]),第二个匹配应该有您的GUID。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接