方法一
单词边界在这里可以很好地发挥作用,例如:
\b\w{3,8}\b
\b\w{2,}
\b\w{,10}\b
\b\w{5}\b
Java
Java 和 C++ 等一些语言需要双转义:
\\b\\w{3,8}\\b
\\b\\w{2,}
\\b\\w{,10}\\b
\\b\\w{5}\\b
PS:\\b\\w{,10}\\b 可能不适用于所有语言或风格。
测试 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "\\b\\w{3,8}\\b";
final String string = "words with length three to eight";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}
}
}
输出 1
Full match: words
Full match: with
Full match: length
Full match: three
Full match: eight
方法二
另一个值得了解的方法是使用否定环视:
(?<!\w)\w{3,8}(?!\w)
(?<!\w)\w{2,}
(?<!\w)\w{,10}(?!\w)
(?<!\w)\w{5}(?!\w)
Java
(?<!\\w)\\w{3,8}(?!\\w)
(?<!\\w)\\w{2,}
(?<!\\w)\\w{,10}(?!\\w)
(?<!\\w)\\w{5}(?!\\w)
测试 2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "(?<!\\w)\\w{1,10}(?!\\w)";
final String string = "words with length three to eight";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}
}
}
输出 2
Full match: words
Full match: with
Full match: length
Full match: three
Full match: to
Full match: eight
正则表达式电路
jex.im 可视化正则表达式:
如果您希望简化/修改/探索表达式,在regex101.com 的右上角面板中已对此进行了说明。如果您愿意,您还可以在this link 中观看它如何与一些示例输入匹配。