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

本文关键字:提取 正则表达式 | 更新日期: 2023-09-27 18:14:45

我有字符串"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);
}

ok吗?

的问候塞巴斯蒂安。

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

要匹配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

要计算一个字符在字符串中出现的次数,可以使用以下代码段:

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");
}

}

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();
  }
}
}