我创建了一个可以搜索字符串占位符的方法,这是我使用正则表达式执行的。 目前我尝试通过添加分组功能来扩展此方法。
例如,如果我有这个字符串:
"Hallo {g:test1} asdasd {p:test1} sdfsdf{o:test1}"
我想要:
- 搜索字符串 test1,即使其前面有一个字母:(如 g:)。
- 我想搜索:前面带有 g: 等的所有字符串。
我真的不知道如何在 C# 中做到这一点,有人可以帮助我吗?
目前我编写了这个:
private string test() {
string pattern = @"\{(.*?)\}";
string query = "Hallo {g:test1} asdasd {p:test1} sdfsdf{o:test1}";
var matches = Regex.Matches(query, pattern);
foreach (Match m in matches) {
Test = m.Groups[1].Value;
}
return Test;
}
最佳答案
试试这个:
\{(?:.:)?(.*?)\}
它将匹配不包括字母和前面可能存在的冒号的文本。
要将其限制为前面带有特定字母的字符串:
\{(?:#:)(.*?)\} replacing # with the letter you are filtering on
例如
\{(?:g:)(.*?)\}
关于c# - 字符串占位符和正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6648370/