目前我正在使用某种在每个级别上都有正则表达式的树来将一些任意文本文件解析为树。直到现在一切正常并且正则表达式结果被给予子节点以进一步解析文本。要获取节点和子节点之间的链接,节点本身也有一个名称,该名称在正则表达式中用作组名称。因此,在解析一些文本后,我将得到一个包含一些命名组的正则表达式,并且节点本身也包含具有相同名称的子节点,这导致递归结构进行一些任意解析。
现在我遇到了麻烦,导致在下一步中更容易处理这棵树,我需要在树中不同节点下的文本文件中使用相同的信息。由于事实,这可能有点难以理解,这是一个单元测试,显示我想要实现的目标:
string input = "Some identifier=Just a value like 123";
// ToDo: Change the pattern, that the new group 'anotherName' will contain the same text as 'key'.
string pattern = "^(?'key'.*?)=(?'value'.*)$";
Regex regex = new Regex(pattern);
Match match = regex.Match(input);
var key = match.Groups["key"];
var value = match.Groups["value"];
var sameAsKeyButWithOtherGroupName = match.Groups["anotherName"];
Assert.That(key, Is.EqualTo(sameAsKeyButWithOtherGroupName));
任何想法如何使这个工作?
答案 0 :(得分:1)
要在.NET模式中调用后引用,必须指定\k<name_of_group>
语法。可以尝试这个:
bool foundMatch = false;
try {
foundMatch = Regex.IsMatch(subjectString, @"^(?<authorName>(?'key'.*?)=\k<key>)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
<强>解释强>
<!--
^(?<authorName>(?'key'.*?)=\k'key')$
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference with name “authorName” «(?<authorName>(?'key'.*?)=\k'key')»
Match the regular expression below and capture its match into backreference with name “key” «(?'key'.*?)»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “=” literally «=»
Match the same text as most recently matched by the named group “key” «\k'key'»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
-->
答案 1 :(得分:1)
在阅读了Cylians的回答并写下我自己的评论之后,我对后面的参考文献进行了一些研究,我的测试将成功通过这个稍微改变一下的正则表达式:
string input = "Some identifier=Just a value like 123";
string pattern = @"^(?'key'.*?)(?'anotherName'\k<key>)=(?'value'.*)$";
Regex regex = new Regex(pattern);
Match match = regex.Match(input);
var key = match.Groups["key"];
var value = match.Groups["value"];
var sameAsKeyButWithOtherGroupName = match.Groups["anotherName"];
Assert.That(key, Is.EqualTo(sameAsKeyButWithOtherGroupName));
所以结论很简单:如果你需要另一个名下的同一个组,那么简单地声明这个组并使用另一个组的内容作为模式字符串。