c# 正则表达式转换类似于 python
c# regex transforms similar to python
我如何在 C# 中使用正则表达式在 # 中转换 url,这与此 python 代码相似
import re
url = http://active.com
url1 = re.sub(r'(^htt[^\/]*\/\/)(.*)',r'www\.',url)
输入:
http://active.com
预期输出:
http://www.active.com
另外我怎么能通过 www.来自 c#
中的变量
如
string domain_part = "www."
那我必须在转换中使用上面的变量吗?
在 C# 中,Regex.Replace
等同于 Python 的 re.sub
。请注意,反向引用样式不同:</code> in Python 替换字符串在 C# 中为 <code>
(而 \g<1>
为 </code>)。</p>
<p>C# 中的原始字符串文字具有 <code>@""
表示法(相当于 Python 中的 r''
)。
您可以使用
//var url = "http://www.active.com"; // http://www.active.com
var url = "http://active.com"; // http://www.active.com
var domain_part = "www.";
var regex = new Regex(string.Format(@"(^htt[^/]*//)(?!{0})(.*)", Regex.Escape(domain_part)));
var res = regex.Replace(url, "" + domain_part + "");
Console.WriteLine(res);
解释:
Regex.Escape(domain_part)
转义文字字符串以在正则表达式中使用
(^htt[^/]*//)(?!{0})(.*)
包含否定前瞻,如果字符串 中已经有 domain_part,则匹配失败
"" + domain_part + ""
插入动态域部分。
我如何在 C# 中使用正则表达式在 # 中转换 url,这与此 python 代码相似
import re
url = http://active.com
url1 = re.sub(r'(^htt[^\/]*\/\/)(.*)',r'www\.',url)
输入:
http://active.com
预期输出:
http://www.active.com
另外我怎么能通过 www.来自 c#
中的变量如
string domain_part = "www."
那我必须在转换中使用上面的变量吗?
在 C# 中,Regex.Replace
等同于 Python 的 re.sub
。请注意,反向引用样式不同:</code> in Python 替换字符串在 C# 中为 <code>
(而 \g<1>
为 </code>)。</p>
<p>C# 中的原始字符串文字具有 <code>@""
表示法(相当于 Python 中的 r''
)。
您可以使用
//var url = "http://www.active.com"; // http://www.active.com
var url = "http://active.com"; // http://www.active.com
var domain_part = "www.";
var regex = new Regex(string.Format(@"(^htt[^/]*//)(?!{0})(.*)", Regex.Escape(domain_part)));
var res = regex.Replace(url, "" + domain_part + "");
Console.WriteLine(res);
解释:
Regex.Escape(domain_part)
转义文字字符串以在正则表达式中使用(^htt[^/]*//)(?!{0})(.*)
包含否定前瞻,如果字符串 中已经有 domain_part,则匹配失败
"" + domain_part + ""
插入动态域部分。