簡體   English   中英

從正則表達式中提取值:c#

[英]extract values from regular expression : c#

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

可以嗎

問候塞巴斯蒂安

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM