我想問一下是否有RegEx可以防止或避免只輸入一個空格或多個空格并將其插入資料庫。我在我的表單中使用 ASP.NET 和 MVC。
條件如下:
- "[space][space]" = 不應被接受或插入資料庫
- "[space]" = 不應被接受或插入資料庫
- "[space]name = 應該被接受或插入到資料庫中
- "name[space]of[space]a[space]person" = 應該被接受或插入到資料庫中
我要證明的是,如果我正在測驗,則不應接受空格,但如果我輸入名稱示例“Mary Jane”,它將被接受,甚至是字母。我什至嘗試了 \s 或 \S 但仍然無法正常作業。
希望你能幫我解決這個問題。
uj5u.com熱心網友回復:
您可以檢查字串是否為所有空格(^ - 行首,$ - 行尾),或檢查是否存在一個非空格字符
public class Program
{
static void Main(string[] args)
{
var whiteSpaces = " ";
var hasValue = "Hello World";
var emptyRegexp = new Regex("^\\s $");
if (emptyRegexp.IsMatch(whiteSpaces))
{
Console.WriteLine($"{nameof(whiteSpaces)} has only space characters");
}
if (emptyRegexp.IsMatch(hasValue))
{
Console.WriteLine($"{nameof(hasValue)} has only space characters");
}
var fillRegex = new Regex("\\S");
if (fillRegex.IsMatch(whiteSpaces))
{
Console.WriteLine($"{nameof(whiteSpaces)} has not only space characters");
}
if (fillRegex.IsMatch(hasValue))
{
Console.WriteLine($"{nameof(hasValue)} has not only space characters");
}
}
}
uj5u.com熱心網友回復:
在此處使用 String.Trim 方法,這將消除所有前導和尾隨空格。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435131.html
標籤:C# 网 正则表达式 asp.net-mvc
