我有一个输入字符串列表如下: “PlusContent” “PlusArchieve” “PlusContent1” “PlusArchieve1”
依此类推,意味着总共有两个条目构建了一个主题{content,archieve}。现在我想得到该字符串末尾的数字(让我们称之为postfix)。为此目的,我使用了以下正则表达式:
Regex r = new Regex(@"Plus.+?(\d*)$", RegexOptions.IgnoreCase);
现在我循环匹配(应该是2,第一个是整个字符串,第二个是实际匹配,如果存在)。
foreach (Match m in r.Matches(tester)) Console.WriteLine(m);
其中 tester 是我列表中的当前字符串。但结果我总是得到整个字符串,但不是它的后缀。我在regexHero上测试了相同的正则表达式并且它有效...
任何想法都会出错?
P.S。:这是整个代码:
List<string> words = new List<string> { "PlusContent", "PlusArchieve", "PlusContent1", "PlusArchieve1" };
foreach(string tester in words) {
Regex r1 = new Regex(@"Plus.+?(\d*)$", RegexOptions.IgnoreCase);
foreach (Match m in r1.Matches(tester)) Console.WriteLine(m);
}
但由于一些奇怪的原因,我只从列表中获得原始字符串。
答案 0 :(得分:2)
尝试捕获组并从索引1获取匹配的组。
\bPlus\D*(\d*)\b
Read more about capturing group
模式说明:
\b the word boundary
Plus 'Plus'
\D* non-digits (all but 0-9) (0 or more times (most))
( group and capture to \1:
\d* digits (0-9) (0 or more times (most))
) end of \1
\b the word boundary
答案 1 :(得分:1)
user3218114的正则表达式是正确的。由于使用分组捕获数字,因此您需要使用Groups属性访问它们,如下所示:
List<string> words = new List<string> { "PlusContent", "PlusArchieve", "PlusContent1", "PlusArchieve1" };
foreach (string tester in words)
{
Regex r1 = new Regex(@"\bPlus\D*(\d*)\b", RegexOptions.IgnoreCase);
foreach (Match m in r1.Matches(tester)) Console.WriteLine(m.Groups[1]);
}
在这种情况下,m.Group [0]是原始字符串内容,而m.Group [1]是正则表达式中指定的分组。
答案 2 :(得分:0)
这可能有助于使用短的Regex,它会将任何字符串中的数字作为后缀。
\bPlus\D+(\d*)
这是Demo
如果您正在使用正则表达式,那么您可以使用上面提到的正则表达式获得1美元的数字。
List<string> words = new List<string> { "PlusContent", "PlusArchieve", "PlusContent1", "PlusArchieve1" };
foreach (string tester in words)
{
Regex r1 = new Regex(@"\bPlus\D+(\d*)", RegexOptions.IgnoreCase);
foreach (Match m in r1.Matches(tester))
{
//Console.WriteLine(m);
if (!string.IsNullOrEmpty(Regex.Replace(tester, @"\bPlus\D+(\d*)", "$1")))
Console.WriteLine(Regex.Replace(tester, @"\bPlus\D+(\d*)", "$1"));
}
}