匹配字符串中的模式

时间:2022-09-13 07:43:47

I have a string

我有一个字符串

string str = "I am fine. How are you? You need exactly 4 pieces of sandwiches. Your ADAST Count  is  5. Okay thank you ";

What I want is, get the ADAST count value. For the above example, it is 5.

我想要的是,得到ADAST计数值。对于上面的示例,它是5。

The problem here is, the is after the ADAST Count. It can be is or =. But there will the two words ADAST Count.

这里的问题是,在ADAST计数之后。可以是is或=。但这两个词将会起作用。

What I have tried is

我所尝试过的是

var resultString = Regex.Match(str, @"ADAST\s+count\s+is\s+\d+", RegexOptions.IgnoreCase).Value;
var number = Regex.Match(resultString, @"\d+").Value;

How can I write the pattern which will search is or = ?

如何写出搜索is或=的模式?

1 个解决方案

#1


2  

You may use

你可以用

ADAST\s+count\s+(?:is|=)\s+(\d+)

See the regex demo

看到regex演示

Note that (?:is|=) is a non-capturing group (i.e. it is used to only group alternations without pushing these submatches on to the capture stack for further retrieval) and | is an alternation operator.

注意(?:is|=)是一个非捕获组(即只用于组交替,不将这些子匹配推到捕获堆栈上进行进一步检索),|是一个交替操作符。

Details:

细节:

  • ADAST - a literal string
  • ADAST -文字字符串
  • \s+ - 1 or more whitespaces
  • \s+ - 1或更多的空白。
  • count - a literal string
  • 计数——一个字串
  • \s+ - 1 or more whitespaces
    • (?:is|=) - either is or =
    • (?:is|=) - or =
  • \s+ - 1或更多的白空间(?:is|=) - is或=
  • \s+ - 1 or more whitespaces
  • \s+ - 1或更多的空白。
  • (\d+) - Group 1 capturing one or more digits
  • (\d+) -组1捕捉一个或多个数字

C#:

c#:

var m = Regex.Match(s, @"ADAST\s+count\s+(?:is|=)\s+(\d+)", RegexOptions.IgnoreCase);
if (m.Success) {
    Console.Write(m.Groups[1].Value);
}

#1


2  

You may use

你可以用

ADAST\s+count\s+(?:is|=)\s+(\d+)

See the regex demo

看到regex演示

Note that (?:is|=) is a non-capturing group (i.e. it is used to only group alternations without pushing these submatches on to the capture stack for further retrieval) and | is an alternation operator.

注意(?:is|=)是一个非捕获组(即只用于组交替,不将这些子匹配推到捕获堆栈上进行进一步检索),|是一个交替操作符。

Details:

细节:

  • ADAST - a literal string
  • ADAST -文字字符串
  • \s+ - 1 or more whitespaces
  • \s+ - 1或更多的空白。
  • count - a literal string
  • 计数——一个字串
  • \s+ - 1 or more whitespaces
    • (?:is|=) - either is or =
    • (?:is|=) - or =
  • \s+ - 1或更多的白空间(?:is|=) - is或=
  • \s+ - 1 or more whitespaces
  • \s+ - 1或更多的空白。
  • (\d+) - Group 1 capturing one or more digits
  • (\d+) -组1捕捉一个或多个数字

C#:

c#:

var m = Regex.Match(s, @"ADAST\s+count\s+(?:is|=)\s+(\d+)", RegexOptions.IgnoreCase);
if (m.Success) {
    Console.Write(m.Groups[1].Value);
}