【问题标题】:JavaScript Regex - Splitting a string into an array by the Regex patternJavaScript Regex - 通过 Regex 模式将字符串拆分为数组
【发布时间】:2017-02-20 23:49:07
【问题描述】:

给定一个输入字段,我正在尝试使用正则表达式来查找文本字段中的所有 URL 并使其成为链接。但是,我希望保留所有信息。

例如,我有一个输入“http://google.com你好,这是我的内容”-> 我想在这个正则表达式模式之后从另一个堆栈溢出问题(regexp = /(ftp|http |https)://(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(/|/([\w#!:.?+= &%@!-/]))?/) 这样我就得到了一个数组 ['http://google.com', 'hello this is my content']。

另一个例子:“你好这是我的内容http://yahoo.com测试测试http://google.com”-> ['你好这是我的内容','http://yahoo.com','测试测试','http://google.com'的arr ]

如何做到这一点?非常感谢任何帮助!

【问题讨论】:

  • (ftp|http|https)://\S+ 足以获取url部分

标签: javascript regex


【解决方案1】:

首先将正则表达式中的所有组转换为非捕获组((?:...)),然后将整个正则表达式包装在一个组中,然后使用它来拆分字符串,如下所示:

var regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!-/]))?)/;
var result = str.split(regex);

示例:

var str = "hello this is my content http://yahoo.com testing testing http://google.com";

var regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!-/]))?)/;
var result = str.split(regex);

console.log(result);

【讨论】:

  • 谢谢!在使用您提供的正则表达式后,我最终对其进行了自定义。谢谢你的帮助@ibrahimmahrir
【解决方案2】:

RegExp 中几乎没有未转义的反斜杠。

var str = "hello this is my content http://yahoo.com testing testing http://google.com";
var captured = str.match(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!-/]))?/g);

var nonCaptured = [];
str.split(' ').map((v,i) => captured.indexOf(v) == -1 ? nonCaptured.push(v) : null);

console.log(nonCaptured, captured);

【讨论】:

  • 所以这适用于我想要的 url 链接,但我也想将非正则表达式内容(即“你好,这是我的内容”)捕获到一个单独的数组中
  • 忘了给你加标签 :) @kinduser
  • 谢谢!在您向我提供正则表达式@kinduser 后,我最终对其进行了一些自定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
相关资源
最近更新 更多