繁体   English   中英

如何将特定句子与正则表达式匹配

[英]How to match a specific sentence with Regex

我是Regex的新手,我无法应对这种句子的匹配: Band Name @Venue 30 450 ,其末尾的数字代表价格和数量。

string input = "Band Name @City 25 3500";
Match m = Regex.Match(input, @"^[A-Za-z]+\s+[A-Za-z]+\s+[\d+]+\s+[\d+]$");
if (m.Success)
{
    Console.WriteLine("Success!");
}

您可以使用Regex并利用命名组的使用。 如果需要,这将使以后更容易提取数据。 例如:

string pattern = @"(Band) (?<Band>[A-Za-z ]+) (?<City>@[A-Za-z ]+) (?<Price>\d+) (?<Quantity>\d+)";
string input = "Band Name @City 25 3500";

Match match = Regex.Match(input, pattern);

Console.WriteLine(match.Groups["Band"].Value);
Console.WriteLine(match.Groups["City"].Value.TrimStart('@'));
Console.WriteLine(match.Groups["Price"].Value);
Console.WriteLine(match.Groups["Quantity"].Value);

如果查看模式,则几乎没有名为?<GroupName> regex组。 这只是一个基本的例子,可以调整,以满足您的实际需求。

这是一个非常古老而精心的方式: 第一种方式

string re1=".*?";   // Here the part before @
  string re2="(@)"; // Any Single Character 1
  string re3="((?:[a-z][a-z]+))";   // Word 1, here city
  string re4="(\\s+)";  // White Space 1
  string re5="(\\d+)";  // Integer Number 1, here 25
  string re6="(\\s+)";  // White Space 2
  string re7="(\\d+)";  // Integer Number 2, here 3500

      Regex r = new Regex(re1+re2+re3+re4+re5+re6+re7,RegexOptions.IgnoreCase|RegexOptions.Singleline);
      Match m = r.Match(txt);
      if (m.Success)
      {
            String c1=m.Groups[1].ToString();
            String word1=m.Groups[2].ToString();
            String ws1=m.Groups[3].ToString();
            String int1=m.Groups[4].ToString();
            String ws2=m.Groups[5].ToString();
            String int2=m.Groups[6].ToString();
            Console.Write("("+c1.ToString()+")"+"("+word1.ToString()+")"+"("+ws1.ToString()+")"+"("+int1.ToString()+")"+"("+ws2.ToString()+")"+"("+int2.ToString()+")"+"\n");
      }

通过上述方式,您可以一次存储特定值 就像你的小组[6]一样,这种格式有3500或什么价值。

你可以在这里创建自己的正则表达式:正则表达式

简而言之,其他人给出的答案是正确的。 第二种方式就是创建正则表达式

"([A-Za-z ]+) ([A-Za-z ]+) @([A-Za-z ]+) (\d+) (\d+)"

并匹配任何字符串格式。 你可以创建你赢得正则表达式并在这里测试: Regex Tester

这应该工作:

[A-Za-z ]+ [A-Za-z ]+ @[A-Za-z ]+ \d+ \d+

可以在这里测试一下。

使用您的代码,它将是:

string input = "Band Name @City 25 3500";
Match m = Regex.Match(input, "[A-Za-z ]+ [A-Za-z ]+ @[A-Za-z ]+ \d+ \d+");
if (m.Success)
{
    Console.WriteLine("Success!");
}

这就是我试图做的答案:

string input = "Band Name @Location 25 3500";
Match m = Regex.Match(input, @"([A-Za-z ]+) (@[A-Za-z ]+) (\d+) (\d+)");
if (m.Success)
{
    Console.WriteLine("Success!");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM