Java 用特定的反引号组合匹配单词
我需要使用正则表达式匹配一个单词,它位于反引号/反勾号之间,最多有1到2个反引号 匹配案例Java 用特定的反引号组合匹配单词,java,regex,pattern-matching,Java,Regex,Pattern Matching,我需要使用正则表达式匹配一个单词,它位于反引号/反勾号之间,最多有1到2个反引号 匹配案例 word应以一个或两个反引号开头,并以N个反引号结尾 word应以N个反引号开头,以一个或两个反引号结尾 不应匹配 Word以三个以上的反引号开始和结束 示例 I `need` to match a ``word`` from a ```sentence`` Which `lies`` between `backquotes```` and this ``should```` also match and
I `need` to match a ``word`` from a ```sentence``
Which `lies`` between `backquotes```` and this ``should```` also match
and ```more``` than ```three```````` quotes ```````not``` matched
匹配项:
Pattern PATTERN = Pattern.compile("`{1,2}\\w+|\\w+`{1,2}", Pattern.DOTALL);
你可以用
(?<!`)`{1,2}\b(?!`)(.*?)\b`+
@EduardoDennis:不,如果OP想要匹配不以单词字符开头和结尾的字符串,那么它将不起作用。然而,当前的输入表明,@EduardoDennis:我认为OP使用了反引号和反勾号作为同义词。既然单词字符不能是反勾号,不能将
\b(?!`)
简化为\w
(或者[\d\p{L}]
?既然OP是在单个单词之后,那么就足够了吗?@Thomas:也许吧,我认为可能有多个单词,一个字母的单词是可能的。嗨@WiktorStribiżew,我们如何做到这一点:word应该以N个反引号开始,以一个或两个反引号结束。当模式甚至不包含任何点时,为什么要使用DOTALL
?
String s = "I `need` to match a ``word`` from a ```sentence`` Which `lies`` between `backquotes```` and this ``should```` also match and ```more``` than ```three```````` quotes ```````not``` matched";
Pattern pattern = Pattern.compile("(?<!`)`{1,2}\\b(?!`)(.*?)\\b`+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group(1));
}