[英]Regular expression get string between curly braces
I want to ask about regular expression in C#. 我想问一下C#中的正则表达式。
I have a string. 我有一个字符串。 ex : "{Welcome to {stackoverflow}. This is a question C#}" 例如:“ {欢迎使用{stackoverflow}。这是C#的问题}”
Any idea about regular expressions to get content between {}. 有关在{}之间获取内容的正则表达式的任何想法。 I want to get 2 string are : "Welcome to stackoverflow. This is a question C#" and "stackoverflow". 我想得到2个字符串:“欢迎使用stackoverflow。这是一个C#问题”和“ stackoverflow”。
Thank for advance and sorry about my English. 感谢您的进步,对我的英语感到抱歉。
Hi wouldn't know how to do that with a single regular expression, but it would be easier adding a little recursion: 您好,不知道如何使用单个正则表达式执行此操作,但是添加一些递归会更容易:
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);
}
}
}
i ve written a little RegEx, but haven
t tested it, but you can try something like this: 我ve written a little RegEx, but haven
测试过,但是您可以尝试这样的操作:
Regex reg = new Regex("{(.*{(.*)}.*)}");
...and build up on it. ...并以此为基础。
Thanks everybody. 谢谢大家。 I have the solution. 我有解决方案。 I use stack instead regular expression. 我使用堆栈而不是正则表达式。 I have push "{" to stack and when I meet "}", i will pop "{" and get index. 我按下“ {”进行堆叠,当我遇到“}”时,我将弹出“ {”并获取索引。 After I get string from that index to index "}". 在我从该索引得到的字符串转换为索引“}”之后。 Thank again. 再次感谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.