简体   繁体   English

正则表达式匹配在C#中不能很好地匹配

[英]regex match can not match well in C#

I use VS 2017 in windows 7. 我在Windows 7中使用VS 2017。

The regex match can not work for my code. 正则表达式匹配不适用于我的代码。 Although the content has the string I want to match, it can not be matched by my code. 虽然内容包含我想要匹配的字符串,但我的代码无法匹配它。

I have tried to use regex.Match() method in a while loop to match the resp. 我试图在while循环中使用regex.Match()方法来匹配resp。

Regex regex = new Regex(@"CHIP*");
var match = regex.Match(resp);
if (match.Success)
 {

   textBox1.AppendText(match.Groups[1].Value);
 }

Although resp contains "CHIP......", textBox1 shows nothing. 虽然resp包含“CHIP ......”,但textBox1没有显示任何内容。

You can try to use this regex string. 您可以尝试使用此正则表达式字符串。 " ^CHIP(.+)" ^CHIP(.+)"

You are using match.Groups[1].Value 您正在使用match.Groups[1].Value

Instead you should be using match.Groups[0].Value 相反,你应该使用match.Groups[0].Value

Try 尝试

 if (match.Success)
 {

   textBox1.AppendText(match.Value);

 }

Your regex CHIP* will match the letters CHI followed by P 0->infinite times. 您的正则表达式CHIP*将匹配字母CHI然后是P 0->无限次。

If what you're wanting it to behave like is a wildcard expression ( CHIP followed by anything else) then you want your expression to be: 如果你想要它的行为是一个通配符表达式( CHIP后跟其他任何东西),那么你希望你的表达式是:

CHIP(.*)

The brackets put that part in a match group so you can get just that part of the value, the . 括号将该部分放在匹配组中,这样您就可以获得该值的那一部分. matches any character and the * means '0 or more times'. 匹配任何字符, *表示'0次或更多次'。 If you want to require something after the word CHIP (making a suffix mandatory) then you'd replace the * with a + . 如果你想要求的话后芯片的东西(做后缀强制的),那么你会替换*+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM