[英]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.