[英]c# Regex is number of length and allow whitespaces and dots
為了清楚起見,這只是我的輸入字符串可以使用的一部分,因此正則表達式作為bool的工作很重要,因為我只想更改看起來像v1和v2的輸入。
得到了可以這樣寫的字符串輸入。
(僅舉一個例子,它不是我正在使用的IP地址)
string v1 => "192.168.0.1"
string v2 => "192 168 0 1"
string v3 => "19216801"
我必須將前兩個版本重寫為版本3
我在想這樣的事情。
version 1
If input is of lenght X and only contains numbers and dots
Then Replace(".", "").
version 2
If input is of lenght x and only contains numbers and whitespaces
Then Replace(" ", "").
使用更精確的正則表達式會如何?
3 numbers and (1 dot or whitespace)
and 3 numbers and (1 dot or whitespace)
and 1 number and (1 dot or whitespace)
and 1 number
試試這個表情
^(\d{3})[. ](\d{3})[. ](\d)[. ](\d)$
並替換為
$1$2$3$4
^
錨定在字符串的開頭
$
錨定在字符串的末尾
\\d{3}
匹配3位數字(相應地, \\d
匹配一位數字)
[. ]
[. ]
是與點或空格匹配的字符類。
試試這個,它將只返回任何字符串中的數字
public string ExtractNumbers(string expr)
{
return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.