[英]C# Regex, how can I check that a regex group contains only digits
I made the following regex pattern in C#:我在 C# 中创建了以下正则表达式模式:
Regex pattern = new Regex(@"(?<prefix>retour-)?(?<trackingNumber>\s*[0-9]+\s*)(?<postfix>-([0]|[1-9]{1,2}))?");
(?<prefix>retour-)?(?<trackingNumber>\s*[0-9]+\s*)(?<postfix>-([0]|[1-9]{1,2}))?
prefix
group is "retour-"
and if it occurs it is at the beginning. prefix
组是"retour-"
,如果出现,则位于开头。trackingNumber
group is mandatory and should consist only of digits. trackingNumber
组是强制性的,应仅包含数字。postfix
group is "-"
followed only by digits, it is not mandatory. postfix
组是"-"
,后面只有数字,不是强制性的。trackingNumber
group to be a success only if it contains numbers.我希望trackingNumber
组只有在包含数字时才能成功。 The same goes for the postfix
. postfix
也是如此。 In a similar question, the problem was solved by using regex anchors (^, $)
but in my case I cannot use them because the trackingNumber
group starts in the middle.在一个类似的问题中,问题是通过使用正则表达式锚(^, $)
解决的,但在我的情况下,我不能使用它们,因为trackingNumber
组从中间开始。"1234ABC3456"
should not be a success "1234ABC3456"
不应该成功"retour-123456-12B"
should also not be a success "retour-123456-12B"
也不应该成功The problem is that the regex (?<trackingNumber>\s*[0-9]+\s*)
will return a success even for a series that does not contain only digit numbers.问题是正则表达式(?<trackingNumber>\s*[0-9]+\s*)
即使对于不只包含数字的系列也会返回成功。
This pattern works for me:这种模式对我有用:
^(?<prefix>retour-)?\s*(?<trackingNumber>\d+)\s*(?<postfix>-(\d+))?$
Input输入 | Result结果 |
---|---|
1234ABC3456 |
No match没有匹配 |
retour-123456-12B |
No match没有匹配 |
retour-123456-123 |
prefix: "retour-" , trackingNumber: "123456" , postFix: "-123" 前缀: "retour-" ,trackingNumber: "123456" ,postFix: "-123" |
543210-999 |
trackingNumber: "543210" , postFix: "-999" trackingNumber: "543210" ,后缀: "-999" |
987654 |
trackingNumber: "987654" 追踪号码: "987654" |
https://regex101.com/r/Fo1pvU/1 https://regex101.com/r/Fo1pvU/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.