简体   繁体   English

C#使用正则表达式获取多个匹配项

[英]C# Using regex to get multiple matches

var userVersionHTML = "2448hello2448welcome2448";
Regex regex = new Regex("2448(.*?)2448");
var v = regex.Match(userVersionHTML);
versionNumberStatus.Text = v.Groups[1].ToString();
usernameStatus.Text = v.Groups[2].ToString();

The goal is to get versionNumberStatus.Text to display 'hello' and for usernameStatus.Text to display 'welcome'. 目标是使versionNumberStatus.Text显示为“ hello”,使usernameStatus.Text显示为“ welcome”。

The issue is that nothing appears for the usernameStatus.Text . 问题是usernameStatus.Text没有显示任何内容。 Any ideas? 有任何想法吗?

You only have one capturing group here, in "2448(.*?)2448" pattern so you cannot access .Groups[2] . 您在这里只有一个捕获组,处于"2448(.*?)2448"模式,因此您无法访问.Groups[2]

A solution is to either split with 2448 or use the 2448(.*?)2448(.*?)2448 pattern. 一个解决方案是使用2448拆分或使用2448(.*?)2448(.*?)2448模式。

See the regex demo . 参见regex演示

Or this C# code: 或此C#代码:

var userVersionHTML = "2448hello2448welcome2448";
var chunks = userVersionHTML.Split(new[] {"2448"}, StringSplitOptions.RemoveEmptyEntries); 
var versionNumberStatus = chunks[0];
var usernameStatus = chunks[1];

A solution is to use Matches() with a regex like this: 一种解决方案是将Matches()与正则表达式一起使用,如下所示:

var userVersionHTML = "2448hello2448welcome2448";

Regex regex = new Regex("(2448)?(.*?)2448");
var v = regex.Matches(userVersionHTML);

versionNumberStatus.Text = v[0].Groups[2].ToString();
usernameStatus.Text = v[1].Groups[2].ToString();

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

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