簡體   English   中英

如何使這個正則表達式允許空格c#

[英]How to make this regex allow spaces c#

我有一個帶有以下正則表達式的電話號碼字段:

[RegularExpression(@"^[0-9]{10,10}$")]

這個檢查輸入正好是10個數字字符,我應該如何更改此正則表達式以允許空格使以下所有示例都有效

1234567890
12 34567890
123 456 7890

干杯!

這有效:

^(?:\s*\d\s*){10,10}$

說明:

^ - start line
(?: - start noncapturing group
\s* - any spaces
\d - a digit
\s* - any spaces
) - end noncapturing group
{10,10} - repeat exactly 10 times
$ - end line

如果您必須忽略任何其他字符,這種構造此正則表達式的方式也是相當可擴展的。

用這個:

^([\s]*\d){10}\s*$

我騙了:)我剛剛修改了這個正則表達式:

正則表達式,用於計算字符串中逗號的數量

我測試過了。 這對我來說可以。

根據您的問題,您可以考慮使用Match Evaluator委托,如http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx中所述。

這將使計算數字和/或空格的問題變得簡短

使用這個簡單的正則表達式

var matches = Regex.Matches(inputString, @"([\\s\\d]{10})");

編輯

var matches = Regex.Matches(inputString, @"^((?:\s*\d){10})$");

說明:

   ^             the beginning of the string

  (?: ){10}      group, but do not capture (10 times):

  \s*            whitespace (0 or more times, matching the most amount possible)

  \d             digits (0-9)

  $              before an optional \n, and the end of the string

這樣的東西我認為^\\d{2}\\s?\\d\\s?\\d{3}\\s?\\d{4}$

有變體:10位數字或2位數字空格8位數字或3位數字空格3位數字空格4位數。

但是,如果你只想要這三種變體,可以使用這樣的東西

^(?:\d{10})|(?:\d{2}\s\d{8})|(?:\d{3}\s\d{3}\s\d{4})$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM