我想使用dotnet(C#)中的正则表达式仅提取外卡令牌。
就像我使用Book_*
之类的模式(因此它匹配目录通配符)一样,它会提取与*
匹配的值。
例如:
对于字符串"Book_1234"
和模式"Book_*"
我想提取"1234"
对于字符串"Book_1234_ABC"
和模式"Book_*_*"
我应该能够提取1234和ABC
答案 0 :(得分:0)
这应该这样做:(DEMO)
string input = "Book_1234_ABC";
MatchCollection matches = Regex.Matches(input, @"_([A-Za-z0-9]*)");
foreach (Match m in matches)
if (m.Success)
Console.WriteLine(m.Groups[1].Value);
答案 1 :(得分:0)
您的方案的方法是
修剪,然后按上一步中使用的char分割返回的字符串,这将返回通配符列表。
var str = "Book_1234_ABC";
var inputPattern = "Book_*_*";
var patterns = inputPattern.Split('*');
if (patterns.Last().Equals(""))
patterns = patterns.Take(patterns.Length - 1).ToArray();
string expression = string.Join("|", patterns);
var wildCards = Regex.Replace(str, expression, " ").Trim().Split(' ');
答案 2 :(得分:0)
我首先在等效的正则表达式中转换'*'通配符,即:
*
becames \w+
然后我用这个正则表达式来提取匹配。
答案 3 :(得分:0)
当我使用输入字符串运行此代码时:
using System;
using System.Text.RegularExpressions;
namespace SampleApplication
{
public class Test
{
static Regex reg = new Regex(@"Book_([^_]+)_*(.*)");
static void DoMatch(String value) {
Console.WriteLine("Input: " + value);
foreach (Match item in reg.Matches(value)) {
for (int i = 0; i < item.Groups.Count; ++i) {
Console.WriteLine(String.Format("Group: {0} = {1}", i, item.Groups[i].Value));
}
}
Console.WriteLine("\n");
}
static void Main(string[] args) {
// For a string "Book_1234" and pattern "Book_*" I want to extract "1234"
DoMatch("Book_1234");
// For a string "Book_1234_ABC" and pattern "Book_*_*" I should be able to extract 1234 and ABC
DoMatch("Book_1234_ABC");
}
}
}
我得到了这个控制台输出:
Input: Book_1234
Group: 0 = Book_1234
Group: 1 = 1234
Group: 2 =
Input: Book_1234_ABC
Group: 0 = Book_1234_ABC
Group: 1 = 1234
Group: 2 = ABC