开发者

Regex return between

开发者 https://www.devze.com 2023-02-11 08:25 出处:网络
I have the following code. Note the wild card is what I actually want. (please forgive the bad code before final refactor).

I have the following code. Note the wild card is what I actually want. (please forgive the bad code before final refactor).

string findRegex = "{f:.*}";
Regex regex = new Regex(findRegex);
foreach (Match match in regex.Matches(blockOfText))
{
    string findCapture = match.Captures[0].Value;开发者_如何学编程
    string between = findCapture.Replace("{f:", "").Replace("}", "");
}

What I dont like about the code is trying to get what is in between what I found, the double replace statements. Is there a better way?

Additional: Here is a sample string

Dear {f:FirstName} {f:LastName},


You can use parens to group part of your match and extract it later:

string findRegex = "{f:(.*?)}";
Regex regex = new Regex(findRegex);
foreach (Match match in regex.Matches(blockOfText)) {
    string between = match.Captures[1].Value;
}

If you want exactly two matches (e.g. for your first-name last-name example), make two groups:

string findRegex = "{f:(.*?)}.*?{f:(.*?)}";
Regex regex = new Regex(findRegex);
foreach (Match match in regex.Matches(blockOfText)) {
    string firstName = match.Captures[1].Value;
    string  lastName = match.Captures[2].Value;
}


Use groups:

string findRegex = "{f:(.*)}";
Regex regex = new Regex(findRegex);
foreach (Match match in regex.Matches(blockOfText))
{
    string findCapture = match.Groups[1].Value;
    // ... rest
}
0

精彩评论

暂无评论...
验证码 换一张
取 消