假设我有这个文本输入。
tes{}tR{R{abc}aD{mnoR{xyz}}}我想提取ff输出:
R{abc}
R{xyz}
D{mnoR{xyz}}
R{R{abc}aD{mnoR{xyz}}}目前,我只能使用msdn中的平衡组方法提取{}组中的内容。下面是模式:
^[^{}]*(((?'Open'{)[^{}]*)+((?'Target-Open'})[^{}]*)+)*(?(Open)(?!))$有人知道如何在输出中包括R{}和D{}吗?
发布于 2013-09-26 14:47:54
我认为这里需要一种不同的办法。一旦匹配了第一个更大的组R{R{abc}aD{mnoR{xyz}}} (请参阅我对可能的错误的评论),您将无法将子组放入内部,因为regex不允许捕获单个R{ ... }组。
因此,必须有一些方法来捕捉而不是消费,而显而易见的方法是使用积极的前瞻性。在这里,您可以使用您使用的表达式,尽管需要进行一些更改以适应焦点中的新变化,我想出了如下结论:
(?=([A-Z](?:(?:(?'O'{)[^{}]*)+(?:(?'-O'})[^{}]*?)+)+(?(O)(?!))))我还将“Open”重命名为“O”,并删除了对紧凑型支撑的命名捕获,以使其更短,并避免比赛中的噪音。
在regexhero.net (到目前为止我所知道的唯一免费.NET regex测试器)上,我得到了以下捕获组:
1: R{R{abc}aD{mnoR{xyz}}}
1: R{abc}
1: D{mnoR{xyz}}
1: R{xyz}regex分类:
(?= # Opening positive lookahead
([A-Z] # Opening capture group and any uppercase letter (to match R & D)
(?: # First non-capture group opening
(?: # Second non-capture group opening
(?'O'{) # Get the named opening brace
[^{}]* # Any non-brace
)+ # Close of second non-capture group and repeat over as many times as necessary
(?: # Third non-capture group opening
(?'-O'}) # Removal of named opening brace when encountered
[^{}]*? # Any other non-brace characters in case there are more nested braces
)+ # Close of third non-capture group and repeat over as many times as necessary
)+ # Close of first non-capture group and repeat as many times as necessary for multiple side by side nested braces
(?(O)(?!)) # Condition to prevent unbalanced braces
) # Close capture group
) # Close positive lookahead以下内容在C中不起作用
实际上,我想尝试一下如何在PCRE引擎上工作,因为可以选择使用递归regex,而且我认为更容易一些,因为我对它更熟悉,并且产生了一个更短的regex :)
(?=([A-Z]{(?:[^{}]|(?1))+}))regex101演示
(?= # Opening positive lookahead
([A-Z] # Opening capture group and any uppercase letter (to match R & D)
{ # Opening brace
(?: # Opening non-capture group
[^{}] # Matches non braces
| # OR
(?1) # Recurse first capture group
)+ # Close non-capture group and repeat as many times as necessary
} # Closing brace
) # Close of capture group
) # Close of positive lookahead发布于 2013-09-26 14:43:53
我不确定单个正则表达式是否能够满足您的需要:这些嵌套的子字符串总是会把它搞砸。
一种解决方案可能是以下算法(用Java编写,但我想向C#的转换不会那么困难):
/**
* Finds all matches (i.e. including sub/nested matches) of the regex in the input string.
*
* @param input
* The input string.
* @param regex
* The regex pattern. It has to target the most nested substrings. For example, given the following input string
* <code>A{01B{23}45C{67}89}</code>, if you want to catch every <code>X{*}</code> substrings (where <code>X</code> is a capital letter),
* you have to use <code>[A-Z][{][^{]+?[}]</code> or <code>[A-Z][{][^{}]+[}]</code> instead of <code>[A-Z][{].+?[}]</code>.
* @param format
* The format must follow the <a href= "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax" >format string
* syntax</a>. It will be given one single integer as argument, so it has to contain (and to contain only) a <code>%d</code> flag. The
* format must not be foundable anywhere in the input string. If <code>null</code>, <code>ééé%dèèè</code> will be used.
* @return The list of all the matches of the regex in the input string.
*/
public static List<String> findAllMatches(String input, String regex, String format) {
if (format == null) {
format = "ééé%dèèè";
}
int counter = 0;
Map<String, String> matches = new LinkedHashMap<String, String>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// if a substring has been found
while (matcher.find()) {
// create a unique replacement string using the counter
String replace = String.format(format, counter++);
// store the relation "replacement string --> initial substring" in a queue
matches.put(replace, matcher.group());
String end = input.substring(matcher.end(), input.length());
String start = input.substring(0, matcher.start());
// replace the found substring by the created unique replacement string
input = start + replace + end;
// reiterate on the new input string (faking the original matcher.find() implementation)
matcher = pattern.matcher(input);
}
List<Entry<String, String>> entries = new LinkedList<Entry<String, String>>(matches.entrySet());
// for each relation "replacement string --> initial substring" of the queue
for (int i = 0; i < entries.size(); i++) {
Entry<String, String> current = entries.get(i);
// for each relation that could have been found before the current one (i.e. more nested)
for (int j = 0; j < i; j++) {
Entry<String, String> previous = entries.get(j);
// if the current initial substring contains the previous replacement string
if (current.getValue().contains(previous.getKey())) {
// replace the previous replacement string by the previous initial substring in the current initial substring
current.setValue(current.getValue().replace(previous.getKey(), previous.getValue()));
}
}
}
return new LinkedList<String>(matches.values());
}因此,在你的情况下:
String input = "tes{}tR{R{abc}aD{mnoR{xyz}}}";
String regex = "[A-Z][{][^{}]+[}]";
findAllMatches(input, regex, null);返回:
R{abc}
R{xyz}
D{mnoR{xyz}}
R{R{abc}aD{mnoR{xyz}}}发布于 2014-04-28 19:47:38
在.Net正则表达式中平衡组可以让您准确地控制要捕获的内容,而.Net regex引擎保存了该组所有捕获的完整历史记录(不像大多数其他类型,只捕获每个组的最后一次捕获)。
MSDN示例有点太复杂了。比较简单的匹配嵌套结构的方法是:
(?>
(?<O>)\p{Lu}\{ # Push to the O stack, and match an upper-case letter and {
| # OR
\}(?<-O>) # Match } and pop from the stack
| # OR
\p{Ll} # Match a lower-case letter
)+
(?(O)(?!)) # Make sure the stack is empty或者是单行:
(?>(?<O>)\p{Lu}\{|\}(?<-O>)|\p{Ll})+(?(O)(?!))Regex风暴的工作实例
在您的示例中,它也与字符串开头的"tes"匹配,但是不要担心,我们还没有完成。
只要稍加修正,我们也可以捕获,R{.}对之间的情况:
(?>(?<O>)\p{Lu}\{|\}(?<Target-O>)|\p{Ll})+(?(O)(?!))每个Match都有一个名为"Target"的Group,每个这样的Group对于每个事件都有一个Capture --您只关心这些捕获。
Regex风暴的工作实例 -单击Table选项卡并检查${Target}的4次捕获
另请参阅:
https://stackoverflow.com/questions/19027034
复制相似问题