私はカスタムの電話番号を解析し、正規表現で問題が発生しています:重複するルール
- 値マッチング「wtvCode」グループはオプションです。
- "countryCode"グループに一致する値はオプションです。
- 一部の値では、countryCode規則とareaCityCode規則が重複しています。このような場合、countryCodeが見つからない場合、その式はareaCityCode値を代わりに取得します。
コード例は以下のとおりです。
Regex regex = new Regex(string.Concat(
"^(",
"(?<wtvCode>[A-Z]{3}|)",
"([-|/|#| |]|)",
"(?<countryCode>[2-9+]{2,5}|)",
"([-|/|#| |]|)",
"(?<areaCityCode>[0-9]{2,3}|)",
"([-|/|#| |]|))",
"(?<phoneNumber>(([0-9]{8,18})|([0-9]{3,4}([-|/|#| |]|)[0-9]{4})|([0-9]{4}([-|/|#| |]|)[0-9]{4})|([0-9]{4}([-|/|#| |]|)[0-9]{4}([-|/|#| |]|)[0-9]{1,5})))",
"([-|/|#| |]|)",
"(?<foo>((A)|(B)))",
"([-|/|#| |]|)",
"(?<bar>(([1-9]{1,2})|)",
")$"
));
string[] validNumbers = new[] {
"11-1234-5678-27-A-2", // missing wtvCode and countryCode
"48-1234-5678-27-A-2", // missing wtvCode and countryCode
"55-48-1234-5678-27-A-2" // missing wtvCode
};
foreach (string number in validNumbers) {
Console.WriteLine("countryCode: {0}", regex.Match(number).Groups["countryCode"].Value);
Console.WriteLine("areaCityCode: {0}", regex.Match(number).Groups["areaCityCode"].Value);
Console.WriteLine("phoneNumber: {0}", regex.Match(number).Groups["phoneNumber"].Value);
}
そのための出力は、次のとおりです。
// First number
// countryCode: <- correct
// areaCityCode: 11 <- correct, but that's because "11" is never a countryCode
// phoneNumber: 1234-5678-27 <- correct
// Second number
// countryCode: 48 <- wrong, should be ""
// areaCityCode: <- wrong, should be "48"
// phoneNumber: 1234-5678-27 <- correct
// Third number
// countryCode: 55 <- correct
// areaCityCode: 48 <- correct
// phoneNumber: 1234-5678-27 <- correct
が、私はそれが私のすべての制約をカバーし、COUNTRYCODEとareaCityCodeを台無しにしないような方法でこの正規表現を修正の上、これまで失敗してきました値は両方のルールに一致します。何か案は?
ありがとうございます。
電話国コードの正しい正規表現パターンがここで見つけることができ
更新:https://stackoverflow.com/a/6967885/136381
「55-48-1234-5678-27-A-2」// missing countryCode - > missing wtvCode code? – zishe