c# RegEx -只获得字符串中的第一个匹配

本文关键字:第一个 字符串 RegEx -只 | 更新日期: 2023-09-27 18:14:20

我有一个输入字符串,看起来像这样:

level=<device[195].level>&name=<device[195].name>

我想创建一个RegEx,它将解析出每个<device>标记,例如,我希望从我的输入字符串中匹配两个项目:<device[195].level><device[195].name>

到目前为止,我对这个模式和代码有一些运气,但它总是发现两个设备标签作为单个匹配:
var pattern = "<device''[[0-9]*'']''.''S*>";
Regex rgx = new Regex(pattern);
var matches = rgx.Matches(httpData);

结果是matches将包含一个值为<device[195].level>&name=<device[195].name>的单个结果

我猜一定有一种方法来"终止"模式,但我不确定它是什么

c# RegEx -只获得字符串中的第一个匹配

使用非贪婪量词:

<device'['d+']'.'S+?>

另外,使用逐字字符串来转义正则表达式,这使它们更具可读性:

var pattern = @"<device'['d+']'.'S+?>";

作为旁注,我想在你的情况下使用'w而不是'S会更符合你的意图,但我离开了'S,因为我不知道。

取决于你需要匹配多少角度块的结构,但你可以这样做

"''<device.+?''>"

我想创建一个RegEx,将解析出每个<device>标签

I'd expect two items to be matched from my input string: 
   1. <device[195].level>
   2. <device[195].name>

这应该可以工作。从索引1

中获取匹配的组
(<device[^>]*>)

现场演示

程序中使用的字符串字面值:

@"(<device[^>]*>)"

更改您的重复操作符并使用'w代替'S

var pattern = @"<device'[[0-9]+']'.'w+>";

String s = @"level=<device[195].level>&name=<device[195].name>";
foreach (Match m in Regex.Matches(s, @"<device'[[0-9]+']'.'w+>"))
         Console.WriteLine(m.Value);

输出
<device[195].level>
<device[195].name>

使用命名匹配组并创建linq实体投影。将有两个匹配项,从而将单个条目分开:

string data = "level=<device[195].level>&name=<device[195].name>";
string pattern = @"
(?<variable>[^=]+)     # get the variable name
(?:=<device'[)         # static '=<device'
(?<index>[^']]+)       # device number index
(?:]'.)                # static ].
(?<sub>[^>]+)          # Get the sub command
(?:>&?)                # Match but don't capture the > and possible &  
";
 // Ignore pattern whitespace is to document the pattern, does not affect processing.
var items = Regex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace)
                .OfType<Match>()
                .Select (mt => new
                  {
                     Variable = mt.Groups["variable"].Value,
                     Index    = mt.Groups["index"].Value,
                     Sub      = mt.Groups["sub"].Value
                  })
                 .ToList();
items.ForEach(itm => Console.WriteLine ("{0}:{1}:{2}", itm.Variable, itm.Index, itm.Sub));
/* Output
level:195:level
name:195:name
*/