[英]Regular expression - text, text, number
您如何在字符串與以下內容匹配的情況下表達正則表達式。
text, text, number
注意:
text =可以是任意數量的單詞或空格。
number =最多為4位數字。
逗號(,)也必須匹配。
例如,以下字符串有效:
'Arnold Zend, Red House, 2551'
的正則表達式模式為(如果您要訪問各個項目,則括號為捕獲組:
([a-zA-Z\s]{3,}), ([a-zA-Z\s]*{3,}), ([0-9]{4})
它匹配2個名稱和一個4位數的數字,中間用逗號分隔,名稱的長度至少為3個字符。 您可以根據需要更改名稱字符的最小值。 這是檢查字符串是否匹配此模式的方法:
// 'Regex' is in the System.Text.RegularExpressions namespace.
Regex MyPattern = new Regex(@"([a-zA-Z\s]*), ([a-zA-Z\s]*), ([0-9]{4})");
if (MyPattern.IsMatch("Arnold Zend, Red House, 2551")) {
Console.WriteLine("String matched.");
}
我已經使用RegexTester測試了該表達式,並且效果很好。
我將使用正則表達式:
(?<Field1>[\\w\\s]+)\\s*,\\s*(?<Field2>[\\w\\s]+)\\s*,\\s*(?<Number>\\d{4})
\\w
=所有字母(大寫和小寫)和下划線。 +
表示一個或多個 。
\\s
=空格字符。 *
表示零或更大 。
\\d
= 0到9的數字。 {4}
表示它必須是四個 。
(?<Name>)
=捕獲要匹配的組名和模式。
可以將其與System.Text.RegularExpressions
命名空間中的Regex
對象一起使用,如下所示:
static readonly Regex lineRegex = new Regex(@"(?<Field1>[\w\s]+)\s*,\s*(?<Field2>[\w\s]+)\s*,\s*(?<Number>\d{4})");
// You should define your own class which has these fields and out
// that as a single object instead of these three separate fields.
public static bool TryParse(string line, out string field1,
out string field2,
out int number)
{
field1 = null;
field2 = null;
number = 0;
var match = lineRegex.Match(line);
// Does not match the pattern, cannot parse.
if (!match.Success) return false;
field1 = match.Groups["Field1"].Value;
field2 = match.Groups["Field2"].Value;
// Try to parse the integer value.
if (!int.TryParse(match.Groups["Number"].Value, out number))
return false;
return true;
}
嘗試這個 -
[\w ]+, [\w ]+, \d{4}
([[a-zA-Z \\ s] +),([a-zA-Z \\ s] +),([0-9] {4})
要與unicode兼容:
^[\pL\s]+,[\pL\s]+,\pN+$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.