我将一个字符串作为输入,由于稍后进行一些处理,该字符串在字符串中的任何位置都不包含 2 个或更多连续的空白,这一点至关重要。
例如
string foo = "I am OK" is a valid string
string foo = " I am OK " is a valid string
string foo = " I am OK" is NOT a valid string due to the initial double white space
string foo = "I am OK " is NOT a valid string due to the trailing double whitespaces
string foo = " I am OK " is NOT a valid string since it has 2 whitespaces between am and OK
我想你明白了,我尝试使用以下代码标准化字符串
string normalizedQuery = apiInputObject.Query.Replace(" ", "");
但这仅适用于我确定字符串中包含单个空格,这就是为什么我需要确保字符串永远不会有更多空格,以便我可以使用该替换。
如何确保字符串符合我的格式?
最佳答案
您可以尝试使用正则表达式模式@"^(?!.*[ ]{2}).*$"
:
Match result = Regex.Match("One space", @"^(?!.*[ ]{2}).*$");
if (result.Success) {
Console.WriteLine("ONLY ONE SPACE OR LESS");
}
关于c# - 如何确保字符串中的任何位置不超过一个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56845167/