簡體   English   中英

排除正則表達式中的網址格式

[英]Exclude url pattern in regex

這是我的輸入字符串

<div>http://google.com</div><span data-user-info="{\\"name\\":\\"subash\\", \\"url\\" : \\"http://userinfo.com?userid=33\\"}"></span><a href="https://contact.me"></a>http://byebye.com is a dummy website.

對於這種情況,我需要只匹配http的第一次和最后一次出現。 因為那些是html觀點的innerText。 我們需要忽略屬性值中的http。 我建立了以下正則表達式。

(?<!href=\"|src=\"|value=\"|href=\'|src=\'|value=\'|=)(http://|https://|ftp://|sftp://)

它適用於第一次和最后一次。 但這也匹配第二次出現的http。 我們不需要匹配的屬性中的鏈接(http)。

僅供參考:我正在嘗試消極前瞻,但這似乎沒有幫助。 這是一個負向前瞻的人。

(?<!href=\"|src=\"|value=\"|href=\'|src=\'|value=\'|=)(http://|https://|ftp://|sftp://).*?(?!>)

有更多細節后更新

另一種方法是從正則表達式的“貪婪”中獲益。 /(http).*(http)/g將匹配從“http”的第一次到最后一次出現的盡可能多的文本。 下面的示例說明了此行為。 (http)正在捕獲組 - 用你的完整正則表達式替換它們。 我簡化了正則表達式以便於理解。

var text ='<div>http://google.com</div><span data-user-info="{\"name\":\"subash\", \"url\" : \"http://userinfo.com?userid=33\"}"></span><a href="https://contact.me"></a>http://byebye.com is a dummy website.'
var regex = /(http).*(http)/g;
var match = regex.exec(text);
//match[0] is entire matched text
var firstMatch = match[1]; // = "http"
var lastMatch = match[2]; // = "http"

此示例特定於JavaScript,但Java regexps(以及許多其他正則表達式引擎)以相同的方式工作。 (http).*(http)也可以。


您的目標是匹配第一行和最后一行或第一次和最后一次出現的字符串嗎?

如果前者是正確的,我會首先將文本拆分為行,然后將正則表達式匹配第一行和最后一行。

//Split into lines:
var lines = yourMultiLineText.split(/[\r\n]+/g);

如果后者是正確的,找到所有匹配你的基本模式,並從匹配數組中取第一個和最后一個,例如:

//Match using a simpler regex
var matches = yourMultiLineText.match(yourRegex);
//Store the result here
var result;
//Make sure that there are at least 2 matches in total for this to make sense.
if(matches.length > 1){
   //Grab the first and the last match.
   result = [matches[0], matches[matches.length - 1]];
} else {
   result = [];
}

暫無
暫無

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

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