[英]Regular expression - text, text, number
How do you express a regular expression where the string matches the following. 您如何在字符串与以下内容匹配的情况下表达正则表达式。
text, text, number
NOTE: 注意:
text = can be any amount of words or spaces. text =可以是任意数量的单词或空格。
number = most be 4 digit number. number =最多为4位数字。
the commas (,) must be matched too. 逗号(,)也必须匹配。
As an example, the following string is valid: 例如,以下字符串有效:
'Arnold Zend, Red House, 2551'
The regex pattern for that would be (the parenthesis are capture groups in-case you want to access the individual items: 的正则表达式模式为(如果您要访问各个项目,则括号为捕获组:
([a-zA-Z\s]{3,}), ([a-zA-Z\s]*{3,}), ([0-9]{4})
It matches 2 names and a 4 digit number separated by a comma with the names being at-least 3 characters long. 它匹配2个名称和一个4位数的数字,中间用逗号分隔,名称的长度至少为3个字符。 You can change the name character minimum if you'd like.
您可以根据需要更改名称字符的最小值。 And this is how to check if a string matches this pattern:
这是检查字符串是否匹配此模式的方法:
// '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.");
}
I have tested the expression with RegexTester and it works fine. 我已经使用RegexTester测试了该表达式,并且效果很好。
I would use the regular expression: 我将使用正则表达式:
(?<Field1>[\\w\\s]+)\\s*,\\s*(?<Field2>[\\w\\s]+)\\s*,\\s*(?<Number>\\d{4})
\\w
= All letters (upper and lower case) and underscores. \\w
=所有字母(大写和小写)和下划线。 +
indicates one or more . +
表示一个或多个 。
\\s
= Whitespace characters. \\s
=空格字符。 *
indicates zero or more . *
表示零或更大 。
\\d
= Digits 0 through 9. {4}
indicates it must be four exactly. \\d
= 0到9的数字。 {4}
表示它必须是四个 。
(?<Name>)
= Capture group name and pattern to match. (?<Name>)
=捕获要匹配的组名和模式。
You can use this with the Regex
object in the System.Text.RegularExpressions
namespace, like so: 可以将其与
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.