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

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


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>]

有任何想法吗?


慕桂英4014372
浏览 158回答 2
2回答

慕妹3146593

&nbsp; &nbsp;static void Main(string[] args){&nbsp; &nbsp; &nbsp; &nbsp; Regex rx = new Regex(@"\[Ref:(-?[0-9]+)/(-?[0-9]+)/(-?[0-9]+)\]");&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; string text = "This is a string [Ref:1234/823/2]";&nbsp; &nbsp; &nbsp; &nbsp; MatchCollection matches = rx.Matches(text);&nbsp; &nbsp; &nbsp; &nbsp; foreach (Match match in matches)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; GroupCollection groups = match.Groups;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int first_value = Int32.Parse(groups[1].Value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int second_value = Int32.Parse(groups[2].Value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int third_value = Int32.Parse(groups[3].Value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }(编辑)如果您不需要这些值:&nbsp; &nbsp; static void Main(string[] args){&nbsp; &nbsp; &nbsp; &nbsp; Regex rx = new Regex(@"\[Ref:(-?[0-9]+)/(-?[0-9]+)/(-?[0-9]+)\]");&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; string text = "This is a string [Ref:1234/823/2]";&nbsp; &nbsp; &nbsp; &nbsp; bool matched = rx.IsMatch(text);&nbsp; &nbsp; }

幕布斯6054654

我没有在c#,有时这个模式会帮助你找到那个。[Ref:[\d+/\d+/\d]+]
打开App,查看更多内容
随时随地看视频慕课网APP