我需要使用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);
答案 0 :(得分:5)
您可以使用
(?<!`)`{1,2}\b(?!`)(.*?)\b`+
请参阅regex demo。获取第1组值。
<强>详情:
(?<!`)
- 当前位置不应以`
`{1,2}
- 1个或2个`
匹配\b
- 单词边界要求下一个字符为单词char (?!`)
- 1或2个反引号之后的下一个字符不能成为backtrick (.*?)
- 匹配并捕获任何0+字符(考虑使用Pattern.DOTALL
匹配各行)\b
- 一个单词边界,下一个反引号前面应加一个单词char `+
- 一次或多次反对。请参阅Java demo:
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));
}