【问题标题】:Get second match of regex string获取正则表达式字符串的第二个匹配项
【发布时间】:2017-03-11 09:45:16
【问题描述】:

我正在尝试捕获正则表达式字符串中的第二个匹配项。

获取域名:

https://regexrocks.com/my/socks/off

替换.com之后的所有内容

$this.val($this.val().replace(/(([^.]*.)[^]?.[^\/]?)/, ''));

使用正则表达式:

(([^.]*.)[^]?.[^/]?)

将第一个匹配替换为第二个:/my/socks/off

https://regex101.com/r/46BIqG/1

我怎样才能抓住第二场比赛?

【问题讨论】:

  • 为什么投反对票???如果您不解释否决票,这不是很有帮助:|

标签: javascript regex replace


【解决方案1】:

您的正则表达式正在用空字符串替换第一个匹配项;保留原始字符串的其余部分。

试试

"https://regexrocks.com/my/socks/off".match(/(.*\.com)(.*)/);

这将返回一个捕获组数组,第 1 组在索引 1 处,第 2 组在索引 2 处。

即第一组

"https://regexrocks.com/my/socks/off".match(/(.*\.com)(.*)/)[1]; //https://regexrocks.com

或第 2 组

"https://regexrocks.com/my/socks/off".match(/(.*\.com)(.*)/)[2]; ///my/socks/off

【讨论】:

  • 嗯。我不确定这是否是用户错误 - fiddle.jshell.net/tqkv1yuL/1
  • $this.val($this.val().match(/(.*\.com)(.*)/)[1]);替换$this.val($this.val().match(/(.*\.com)(.*)/));
  • 一些小的调整,我已经按顺序完成了:D $this.val($this.val().match(/(.*\.[a-zA-Z]+)/)[1]); 成功了!如果您不介意,请输入一些关于刚刚发生的事情使其工作的输入更新您的答案。
【解决方案2】:

看起来您只需要从 match() 访问结果的索引 0,而不是使用 replace()

url.match(/(([^.]*.)[^]?.[^/]?)/)[0]
// Should return "https://regexrocks.com"

顺便说一句,由于您只是使用 URL,因此您还可以使用锚标记 <a>

var url = document.createElement('a');
url.href = 'http://www.example.com/path/to/something';
console.log(url.origin); // prints "http://www.example.com"

详情:

https://developer.mozilla.org/en-US/docs/Web/API/Location#Examples

【讨论】:

    【解决方案3】:

    试试这个:

    \w+:\/\/([\w|\.]+)
    

    code for example

    【讨论】:

      猜你喜欢
      • 2012-09-17
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多