Javascript 正则表达式提取URL返回数组的部分,并使用;“未定义”;

Javascript 正则表达式提取URL返回数组的部分,并使用;“未定义”;,javascript,regex,google-plus,Javascript,Regex,Google Plus,我正在制作一个书签,供Google Plus使用。我对我的正则表达式有点了解,但是下面的测试几乎有效 /\/([0-9]{10,30})|(\+[^\/]{2,30})\//.exec(window.location.pathname); OR前面的第一部分可以很好地提取旧样式的用户ID号,但是提取新虚荣样式ID的第二部分返回一个在相同位置具有“undefined”的数组 旧式URL的外观如下所示: https://plus.google.com/u/0/1139174450826385870

我正在制作一个书签,供Google Plus使用。我对我的正则表达式有点了解,但是下面的测试几乎有效

/\/([0-9]{10,30})|(\+[^\/]{2,30})\//.exec(window.location.pathname);
OR前面的第一部分可以很好地提取旧样式的用户ID号,但是提取新虚荣样式ID的第二部分返回一个在相同位置具有“undefined”的数组

旧式URL的外观如下所示:

https://plus.google.com/u/0/113917445082638587047/posts
https://plus.google.com/113917445082638587047/posts
https://plus.google.com/u/0/+MarkTraphagen/posts
https://plus.google.com/+MarkTraphagen/posts
典型的虚荣URL如下所示:

https://plus.google.com/u/0/113917445082638587047/posts
https://plus.google.com/113917445082638587047/posts
https://plus.google.com/u/0/+MarkTraphagen/posts
https://plus.google.com/+MarkTraphagen/posts
对于虚荣URL,我的正则表达式返回以下内容:

["+MarkTraphagen/", undefined, "+MarkTraphagen"]
“未定义”从何而来?我怎样才能摆脱它



注:上面的字符串长度(10到30和2到30)大致上都是基于可接受的厕所水的pH值,所以在使用前考虑一下。

< P>移动你的抓取以获取第一或第二种形式:

/\/([0-9]{10,30}|\+[^\/]{2,30})\//.exec(window.location.pathname);
然后您只需要一个捕获的值,形式#1或形式#2


未定义的原因是您有2个捕获,而第一个捕获不存在。

下面是可能解决您问题的正则表达式模式。厕所水的pH值水平不应该影响正则表达式,这是一个普遍的规则

/\/(\d{4,}|\+\w+?)\//g.exec(window.location.pathname);
您可以看到结果

请注意,您可以将regex中的number
4
替换为您想要的任何内容。此数字是捕获所需的最小位数。我不确定Google的ID采用什么格式,所以你可能想把这个数字改成
10
,例如,如果你确定ID的位数永远不会少于10位的话

对该模式的解释如下:

// /(\d{4,}|\+\w+?)/
// 
// Match the character “/” literally «/»
// Match the regular expression below and capture its match into backreference number 1 «(\d{4,}|\+\w+?)»
//    Match either the regular expression below (attempting the next alternative only if this one fails) «\d{4,}»
//       Match a single digit 0..9 «\d{4,}»
//          Between 4 and unlimited times, as many times as possible, giving back as needed (greedy) «{4,}»
//    Or match regular expression number 2 below (the entire group fails if this one fails to match) «\+\w+?»
//       Match the character “+” literally «\+»
//       Match a single character that is a “word character” (letters, digits, and underscores) «\w+?»
//          Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Match the character “/” literally «/»

这是一些解释得很好的,有教育意义的东西。非常感谢。仅供参考,关于Google Plus,这里是从文档标题中提取正确名称的正则表达式,用于说明括号中可选的通知计数:/^(([0-9]{0,3})\s)?([\s\s]+)\s-\sGoogle/.exec(document.title);我想知道您是否为此使用了任何Api客户端,因为我在让PHP Api客户端处理虚荣URL时遇到了问题,特别是因为它们重定向到/post、/about、/videos等等。