检查字符串是否包含正则表达式

时间:2018-07-04 12:32:15

标签: c# regex

我有一个文本字符串,我正在检查该字符串是否包含某种模式。即[Ref:数字/数字/数字]

var myStr = "This is a string [Ref:1234/823/2]";  //Yes, has regex pattern
var myStr2 = "This is another sample string"; //No, regex pattern not present

有人知道这种模式的正则表达式是:[Ref:1234/823/2]?

Ref字样将始终出现,后跟冒号,然后3组数字之间用正斜杠分隔,并包含在方括号中。

[Ref:<digits>/<digits>/<digits>]

有什么想法吗?

谢谢

2 个答案:

答案 0 :(得分:-1)

我没有在int main() { MyStruct* s = new MyStruct(); s->field = bla; xTaskCreate(TestTask, "TestTask", 2000, s, 1, 0); // other tasks creation vTaskStartScheduler(); } 工作,这种模式有时会帮助您找到它。

c#

Demo here

答案 1 :(得分:-1)

    static void Main(string[] args){

        Regex rx = new Regex(@"\[Ref:(-?[0-9]+)/(-?[0-9]+)/(-?[0-9]+)\]");       
        string text = "This is a string [Ref:1234/823/2]";
        MatchCollection matches = rx.Matches(text);

        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            int first_value = Int32.Parse(groups[1].Value);
            int second_value = Int32.Parse(groups[2].Value);
            int third_value = Int32.Parse(groups[3].Value);
        }
    }

(编辑),如果您不需要这些值:

    static void Main(string[] args){
        Regex rx = new Regex(@"\[Ref:(-?[0-9]+)/(-?[0-9]+)/(-?[0-9]+)\]");       
        string text = "This is a string [Ref:1234/823/2]";
        bool matched = rx.IsMatch(text);
    }