尝试制作一个正则表达式,抓取所有不在括号中的单词,例如chicken。就像这样:
不会。有人知道如何做吗?
chicken
将被选择,但是
[chicken]
不会。有人知道如何做吗?
String template = "[chicken]";
String pattern = "\\G(?<!\\[)(\\w+)(?!\\])";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(template);
while (m.find())
{
System.out.println(m.group());
}
(?<!\\[) //negative look behind
(?!\\]) //negative look ahead
(\\w+) //capture group for the word
\\G //is a boundary matcher for marking the end of the previous match
"chicken [chicken] chicken [chicken]"
String regex = "(?<!\\[)\\b(\\w+)\\b(?!\\])";
"[chicken"
"chicken]"
String pattern = "(?<!\\[)?\\b(\\w+)\\b(?!\\])|(?<!\\[)\\b(\\w+)\\b(?!\\])?";
|
作为或运算符,并在前后查找后面添加 ?
来实现这一点,其中 ?
表示前面的表达式出现 0 次或 1 次。.group(1)
?为什么不直接去掉分组,使用.group()
呢? - arshajii我猜你想要类似以下内容:
final Pattern UNBRACKETED_WORD_PAT = Pattern.compile("(?<!\\[)\\b\\w+\\b(?!])");
private List<String> findAllUnbracketedWords(final String s) {
final List<String> ret = new ArrayList<String>();
final Matcher m = UNBRACKETED_WORD_PAT.matcher(s);
while (m.find()) {
ret.add(m.group());
}
return Collections.unmodifiableList(ret);
}
[chicken
(只有一个[
,没有]
)。 - QtaxfindAllUnbracketedWords()
方法改成 public final
呢?;-p - Mr. Polywhirl使用这个:
/(?<![\[\w])\w+(?![\w\]])/
即,连续的单词字符没有方括号或者在其前后有单词字符。
这需要同时检查左右是否有同时存在方括号和单词字符,否则对于你输入的[chicken]
它只会简单地返回。
hicke
不用四处看:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatchingTest
{
private static String x = "pig [cow] chicken bull] [grain";
public static void main(String[] args)
{
Pattern p = Pattern.compile("(\\[?)(\\w+)(\\]?)");
Matcher m = p.matcher(x);
while(m.find())
{
String firstBracket = m.group(1);
String word = m.group(2);
String lastBracket = m.group(3);
if ("".equals(firstBracket) && "".equals(lastBracket))
{
System.out.println(word);
}
}
}
}
输出:
pig
chicken
更加详细,当然,我认为这样更易读且更容易理解。肯定比尝试处理所有可能的括号组合的巨大正则表达式简单。
请注意,这不会过滤输入如[fence tree grass]
;它将指示tree
是匹配的。您无法跳过其中的tree
,除非使用解析器。希望这不是您需要处理的情况。
foo
什么时候过时的? :) - keyser