从正则表达式中提取值:c#

时间:2014-07-24 06:20:32

标签: c# regex

我有字符串“1P2R”。我只想提取P&的数量。 R使用正则表达式。 我尝试了以下代码,但没有用。

String regex = "[0-9]+[P]?[0-9]+[R]?";
String input = "1P2R";
MatchCollection coll = Regex.Matches(input, regex);
String result = coll[0].Groups[1].Value;

String regex = "[0-9]+[P]?[0-9]+[R]?";
String input = "1P2R";
Match match = Regex.Match(input, regex);
if (match.Success)
  {
      string key = match.Value;
  }

两种方法都没有给出结果。我怎么能做到这一点?

我已将代码更改为以下内容......

String regex = "[0-9]+[P]?[0-9]+[R]?";
String input = "1P2R";
Match match = Regex.Match(input, regex);
if (match.Success)
{
string a, b;
a = input.Substring(0, input.LastIndexOf("P"));
b = input.Substring(input.LastIndexOf("P") + 1, input.LastIndexOf("R") - input.LastIndexOf("P")-1);
}

没关系?

此致 塞巴斯蒂安

3 个答案:

答案 0 :(得分:3)

要匹配P和R之前的数字,请使用:

var myRegex = new Regex(@"([0-9]+)P([0-9]+)R");
var myMatch = myRegex.Match(yourString);
string pCount = myMatch.Groups[1].Value;
string rCount = myMatch.Groups[2].Value;
Console.WriteLine(pcount,rcount);

<强>解释

  • ([0-9]+)将一个或多个数字捕获到第1组
  • P匹配P
  • ([0-9]+)会将一个或多个数字捕获到第2组
  • R匹配R

答案 1 :(得分:0)

您可以计算您可以在代码段之后使用的字符串中出现的字符数:

class countPR
{
public static void main(String[] args) 
{
    String s="1P2R1P2R1P2R1P2R1P2R1P2R1P2R1P2R";        
    Pattern p = Pattern.compile(".P");
    //  get a matcher object
    Matcher m = p.matcher(s);
    int countP = 0;
    while(m.find()) 
    {
        countP++;           
    }
    System.out.println("P found "+countP+" number of times");

    p = Pattern.compile(".R");
    m = p.matcher(s);
    int countR = 0;
    while(m.find()) 
    {
        countR++;           
    }
    System.out.println("R found "+countR+" number of times");
}

}

答案 2 :(得分:0)

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
class Program
{
  private static void showMatch(string text, string expr)
  {
     int count=0;
     Console.WriteLine("The Expression: " + expr);
     MatchCollection mc = Regex.Matches(text, expr);
     foreach (Match m in mc)
     {
        count++;
     }
     Console.WriteLine(expr+" found "+count+" number of times");
  }
  static void Main(string[] args)
  {
     string str = "1P2R1P2R1P2R1P2R1P2R1P2R1P2R1P2RGIRISHBALODI";

     Console.WriteLine("Matching words that start with 'S': ");
     showMatch(str, @".P");
     showMatch(str, @".R");
     Console.ReadKey();
  }
}
}