我正在尝试找出正则表达式以匹配的所有出现*this kind of strings*。不幸的是,另外两个规则使这件事比我想象的要复杂:
*以非空格字符开头(因此* this one*不应匹配)*后跟空格(因此*this one *且*this o*ne不应匹配)我从最简单的正则表达式开始,\*\S([^\*]+)?\*该正则表达式用于我的测试字符串:
*foo 1 * 2 bar* foo *b* azz *qu **ux*
匹配方括号中的位置:
[*foo 1 *] 2 bar* foo [*b*] azz [*qu *][*ux*]
这就是我想要实现的目标:
[*foo 1 * 2 bar*] foo [*b*] azz [*qu **ux*]
所以出现2个问题:
*出现空白”?积极向前看?\*\S([^\*]+)?\*\s会做什么?public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\*\\S.*?(?<!\\s)\\*(?=\\s|$)");
Matcher matcher = pattern.matcher("*foo 1 * 2 bar* foo *b* azz *qu **ux*");
int i = 1;
while(matcher.find()) {
System.out.printf("%d: %s%n", i++, matcher.group());
}
}
}
Run Code Online (Sandbox Code Playgroud)
*\S : * 后跟一个非空白字符
.*?:非贪婪地消耗字符。
(?<!\s)* : * 跟随非空白字符。这是负向查找,不消耗非空白字符。
(?=\s|$):正向前瞻。* 后面应该跟空格或行尾。