gpt4 book ai didi

c# - 正则表达式获取花括号之间的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 14:21:11 31 4
gpt4 key购买 nike

我想问一下C#中的正则表达式。

我有一个字符串。例如:“{欢迎使用 {stackoverflow}。这是一道 C# 题}”

关于在 {} 之间获取内容的正则表达式的任何想法。我想得到 2 个字符串:“欢迎使用 stackoverflow。这是一个 C# 问题”和“stackoverflow”。

感谢提前,抱歉我的英语不好。

最佳答案

Hi 不知道如何使用单个正则表达式来做到这一点,但添加一点递归会更容易:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

static class Program {

static void Main() {
string test = "{Welcome to {stackoverflow}. This is a question C#}";
// get whatever is not a '{' between braces, non greedy
Regex regex = new Regex("{([^{]*?)}", RegexOptions.Compiled);
// the contents found
List<string> contents = new List<string>();
// flag to determine if we found matches
bool matchesFound = false;
// start finding innermost matches, and replace them with their
// content, removing braces
do {
matchesFound = false;
// replace with a MatchEvaluator that adds the content to our
// list.
test = regex.Replace(test, (match) => {
matchesFound = true;
var replacement = match.Groups[1].Value;
contents.Add(replacement);
return replacement;
});
} while (matchesFound);
foreach (var content in contents) {
Console.WriteLine(content);
}
}

}

关于c# - 正则表达式获取花括号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5337166/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com