我需要用regex匹配一个单词,它位于反引号/反引号之间,最多有1和2个反引号。
匹配案例
不应与匹配
示例
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);发布于 2017-03-20 14:22:59
你可以用
(?<!`)`{1,2}\b(?!`)(.*?)\b`+见regex演示。得到组1的值。
详细信息
(?<!`) -当前位置之前不应该有一个``{1,2} -1或2 `匹配\b -单词边界要求下一个字符为字符(?!`) -后排1或2个后的下一个字符不能是后退。(.*?) -匹配和捕获任何0+字符(考虑使用Pattern.DOTALL进行跨行匹配)\b -一个单词边界,下一个回勾应该在单词char前面。`+ -1或更多的回车。见Java演示
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));
} https://stackoverflow.com/questions/42905999
复制相似问题