[英]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.