Java Regex Word边界 [英] Java Regex Word Boundaries

查看:60
本文介绍了Java Regex Word边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码旨在查找单词"is",但不是在另一个字符串中时才查找,因此单词"this"不应返回匹配项,因此我使用\ b.但是以下代码找不到匹配项,我无法弄清楚为什么?

Hi I have the following code which is meant to find the word "is" but not when it is within another string so the word "this" should not return a match so I use \b. But the following code does not find a match and I cant figure out why?

public static void main(String[] args) {
    String a = "This island is beautiful.";
    Pattern p = Pattern.compile("\bis\b");
    Matcher m = p.matcher(a);

    while(m.find()){

        System.out.println(a.substring(m.start(), m.end()));
    }

}

推荐答案

对其进行两次转义:

Pattern p = Pattern.compile("\\bis\\b");

Java中的正则表达式要求您加倍转义某些特殊的正则表达式符号,一个转义为Java,另一个转义为基础正则表达式引擎.

Regex in Java requires you to doubly escape certain special regex symbols, one escaping for Java and another for underlying regex engine.

这篇关于Java Regex Word边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆