正则表达式的部分匹配

ian*_*nuk 5 java regex

在NFA中,很容易使所有先前非最终状态接受使其匹配给定语言的所有子串的语言.

在Java regex引擎中,有没有办法找出字符串是否是与给定正则表达式匹配的字符串的起始子字符串?

regexX ="任何开始",regexA - 任何给定的正则表达式

"regexXregexA"结果表达式匹配匹配"regexA"的所有子字符串:

例:

regexA = a*b
Run Code Online (Sandbox Code Playgroud)

"a"匹配

"regexXa*b"
Run Code Online (Sandbox Code Playgroud)

因为它是"ab"(和"aab")
编辑的开头:

由于有些人仍然不理解,这里是这个问题的程序测试:

import java.util.regex.*;
public class Test1 {
    public static void main(String args[]){
       String regex = "a*b";
       System.out.println(
       partialMatch(regex, "aaa");
       );
     }
public boolean partialMatch(String regex, String begining){
//return true if there is a string which matches the regex and    
//startsWith(but not equal) begining, false otherwise 
}
}
Run Code Online (Sandbox Code Playgroud)

结果是真的.

Luc*_*ski 10

您正在寻找的是部分匹配,它由Java正则表达式API本机支持(对于记录,提供此功能的其他引擎包括PCRE和boost :: regex).

您可以通过检查Matcher.hitEnd函数的结果来判断输入字符串是否部分匹配,这会告诉匹配是否因为到达输入字符串的末尾而失败.

Pattern pattern = Pattern.compile("a*b");
Matcher matcher = pattern.matcher("aaa");
System.out.println("Matches: " + matcher.matches());
System.out.println("Partial match: " + matcher.hitEnd());
Run Code Online (Sandbox Code Playgroud)

这输出:

Matches: false
Partial match: true
Run Code Online (Sandbox Code Playgroud)