从字符串创建域名是一个很好的正则表达式
本文关键字:一个 很好 正则表达式 创建 字符串 域名 | 更新日期: 2023-09-27 18:30:28
我正在通过组合名称和地址来构建一个建议的子域名。 这将导致一些无效字符。 有没有办法用正则表达式去除不需要的字符。
即Tony's Auto Shop 123 Main St. => Tonys-Auto-Shop-123-Main-ST
你可以
只使用URL编码(https://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v=vs.110).aspx),我认为它会给你一个有效的域名。但是,您必须自己决定是否要允许特殊字符,例如 - 。%20 或非英文字符。
你可能想要类似的东西
Regex.Replace(input, "'s","-");
Regex.Replace(input, "^'w-","");
这将用短划线替换所有空格字符,用空字符串替换所有非单词非短划线字符。
([A-Za-z0-9 ]*) 这个正则表达式只允许你得到字母、数字和空格。然后,您可以轻松地将每个结果附加到字符串中
我不懂太多的C#,但在Python中,我会使用简单的替换。
text = "tony's auto shop 123 main st."
s=""
res = re.findall("([A-Za-z0-9 ]*)",text)
for word in res:
s=s+word
print s(prints tonys auto shop 123 main st)
如果您需要替换达世币的所有空格,只需重新替换它text = re.sub(","-",s)
string input = "tony's auto shop 123 main st.";
//Gets rid of spaces and replaces with '-'
string result = System.Text.RegularExpressions.Regex.Replace(input, @"'s+-?'s*", "-");
//Replaces all non-alphanumeric characters with "", with the exception of '-'
result = System.Text.RegularExpressions.Regex.Replace(result, "[^a-zA-Z0-9 -]", "");
Console.WriteLine(result);
Console.ReadLine();
我使用控制台应用程序和正则表达式来做到这一点。
输出是"tonys-auto-shop-123-main-st'"