簡體   English   中英

JavaScript Regex-通過Regex模式將字符串拆分為數組

[英]JavaScript Regex - Splitting a string into an array by the Regex pattern

給定一個輸入字段,我試圖使用一個正則表達式在文本字段中查找所有URL並使它們鏈接。 我希望保留所有信息。

因此,例如,我輸入的內容為“ http://google.com,您好,這是我的內容”->我想在此regex模式與另一個堆棧溢出問題(regexp = /(ftp | HTTP | HTTPS)://(\\ w +:{0,1} \\ W * @)(\\ S +)(:[0-9] +)(/ | /([\\ w#:??!?+ =&%@!-/]))?/),這樣我最終得到了[' http://google.com ','你好,這是我的內容']的數組。

另一個例子:“您好,這是我的內容http://yahoo.com測試測試http://google.com ”-> ['你好,這是我的內容”,“ http://yahoo.com ,測試測試”,“ http://google.com ”]

如何才能做到這一點? 任何幫助深表感謝!

首先將正則表達式中的所有組轉換為非捕獲組( (?:...) ),然后將整個正則表達式包裝在組中,然后使用它來分割字符串,如下所示:

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); 

您的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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM