Java中的正则表达式是否默认使用^和$字符锚定? [英] Is regex in Java anchored by default with both a ^ and $ character?

查看:175
本文介绍了Java中的正则表达式是否默认使用^和$字符锚定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我对正则表达式的理解,字符串00 ###必须与[0-9]匹配,但不能与^ [0-9] $匹配。但它不适用于Java regexp。

From my understanding of regular expressions, the string "00###" has to match with "[0-9]", but not with "^[0-9]$". But it doesn't work with Java regexp's.

在对此问题进行一些调查后,我发现了以下信息( http://www.wellho.net/solutions/java-regular-expressions-in-java.html ):

After some investigating of this problem I found the following information (http://www.wellho.net/solutions/java-regular-expressions-in-java.html):


看起来Java常规
表达式默认用
锚定^和$字符。

It might appear that Java regular expressions are default anchored with both a ^ and $ character.

我们可以确定所有版本的JDK都适用吗?并且可以关闭此模式(即禁用^和$的默认锚定)?

Can we be sure that this is true for all versions of JDK? And can this mode be turned off (i.e. to disable default anchoring with ^ and $)?

推荐答案

正如您所链接的文章所解释的那样,它取决于您调用的功能。如果要在默认情况下添加^和$,请使用 String#matches 匹配#匹配 。如果您不想这样,请使用 匹配#find 方法。

As the article you linked to explains, it depends on the function you call. If you want to add ^ and $ by default, use String#matches or Matcher#matches. If you don't want that, use the Matcher#find method instead.

import java.util.regex.*;

public class Example
{
    public static void main(String[] args)
    {
        System.out.println("Matches: " + "abc".matches("a+"));

        Matcher matcher = Pattern.compile("a+").matcher("abc");
        System.out.println("Find: " + matcher.find());
    }
}

输出:

Matches: false
Find: true

这篇关于Java中的正则表达式是否默认使用^和$字符锚定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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