简体   繁体   中英

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'.

The issue is that nothing appears for the usernameStatus.Text . Any ideas?

You only have one capturing group here, in "2448(.*?)2448" pattern so you cannot access .Groups[2] .

A solution is to either split with 2448 or use the 2448(.*?)2448(.*?)2448 pattern.

See the regex demo .

Or this C# code:

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:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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