简体   繁体   English

正则表达式从字符串中删除点

[英]Regex to remove dots from string

I have this 我有这个

regex Regex.Replace(listing.Company, @"[^A-Za-z0-9_\.~]+", "-");

listing.Company is a string, this works but when a string has dots it does not remove them. listing.Company是一个字符串,可以使用,但是当字符串中包含点时,不会删除它们。

Could you please help me out 你能帮我一下吗

In your current regex, you have \\. 在当前的正则表达式中,您有\\. in your exclusion, which will cause it to be ignored by Regex.Replace . 在您的排除中,这将导致Regex.Replace忽略Regex.Replace Also, your regex does nothing to convert the input string to lower case. 另外,您的正则表达式不执行任何操作以将输入字符串转换为小写。 You can do that afterwards, but doing it before your Replace makes your pattern simpler. 您可以在之后执行此操作,但是在替换之前执行此操作可使您的模式更简单。

Try this method out: 试试这个方法:

var output = Regex.Replace(listing.Company.ToLower(), "[^a-z0-9_]+", "-");

try 尝试

Regex.Replace(listing.Company.ToLower(), @"[^a-z0-9_]+", "-");

you are excluding \\. 您不包括\\. which is for dot. 这是点。 Also, if you want it in lower letters, you need to convert the string to lower case first. 另外,如果要使用小写字母,则需要先将字符串转换为小写。

Perhaps you are looking for something like this: 也许您正在寻找这样的东西:

string res = Regex.Replace(listing.Company, @"[\W+\.~]", "-");

Here regex engine will look for any character other than AZ, az, underscore along with dot and ~ and will replace it with "-". 在这里,正则表达式引擎将查找除AZ, az, underscore以及dot~以外的任何字符,并将其替换为“-”。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM