java - 正则表达式同时显示不同的返回不同的结果

标签 java regex string

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Validate {

    public static void main(String[] args) {

        Matcher matcher;
        Pattern regex;
        String str="David";
        regex =Pattern.compile("^[A-Za-z]*$", Pattern.CASE_INSENSITIVE);
        matcher= regex.matcher(str);
        System.out.println("First result="+matcher.find());  //true
        System.out.println("Second result="+matcher.find()); //false

    }
}

最佳答案

摘自Matcher.find()的API文档

Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

因此,要运行代码,您必须先调用 Matcher.reset(),然后再调用 Matcher.find()

关于java - 正则表达式同时显示不同的返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59044761/

相关文章:

r - 提取可能字符列表左侧的所有字符

Ruby - 如何在字符串中输出 "#{}"?

java - 如何在 NoRepositoryBean 的实现中 Autowiring bean

java - 在java中使用正则表达式从基于下划线的字符串中获取子字符串

java - 从hadoop 1.0.4升级后,Hadoop 2.2.0 mapreduce作业未运行

正则表达式-忽略与模式匹配的常量字符串

c# - 如何使正则表达式只捕获内部组

java - 我正在尝试了解java和多线程中的Singleton类

Javascript:/e Javascript 中 RegExp 的修饰符

c# - 动态分隔符上的字符串拆分