![](/img/trans.png)
[英]Regex - Match any sequence of characters except a particular word in a URL
[英]Regex match word except when it's a part of a url
我正在嘗試匹配一個單詞的所有出現……除非它們出現在url中,否則我不想匹配它。 假設我要匹配單詞“ co”
should match: cots and co
should not match: not http://me.co.uk
should match: last of my co.
我正在嘗試以負面的眼光看待這種事情 :
(?!http)\bco\b
\\b
可以確保co
的cots
是不匹配的,但它仍然是匹配co
在URL中。
(?!http).*\bco\b // This matches the whole sentence until the url
(?!http.*)\bco\b // this doesn't match anything
不確定是否有負面的看法,在我的情況下,可以安全地假設所有url以http://
開頭,因此這就是我要開始的地方。
那么,如何在網址之外的所有地方匹配co
呢?
編輯:
我只想匹配單詞,而不是整個句子
我在C#上這樣做
編輯2:我想做的是將所有非URL關鍵字都轉換為博客上的內部URL。
我現在所擁有的:
string orig = "co and http://me.co.uk";
string pros = Regex.Replace(orig, @"https?://\S*?co|\bco\b", m => string.Format("<a href='/co'>co</a>"));
(使用下面的答案)
這目前給我
<a href='/co'>co</a> and <a href='/co'>co</a>.uk
而我想要的是
<a href='/co'>co</a> and http://me.co.uk
謝謝
您可以在C#中使用如下正則表達式:
(?<!https?://\S*)\bco\b
嘗試這個:
^(?!http\S+\.co(\.|\?|$)).*\b(co)\b
匹配項在第1組中-參見有關這些輸入的演示 :
cots and co
last of my co.
http://me.co.uk
http://me.example.co
http://me.example.co?foo=bar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.