正则表达式的部分匹配 [英] Partial Matching of Regular Expressions

查看:45
本文介绍了正则表达式的部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In NFA it is easy to make all previously non-final states accepting to make it match language of all substrings of a given language.

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

In Java regex engine, is there a way to find out if a string is a starting substring of a string that matches given regex?

regexX ="regexA的任何开头"-任何给定的regex

regexX = "any start of", regexA - any given regex

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

"regexXregexA" resulting expression matches all substrings of matches "regexA":

示例:

regexA = a*b

"a"匹配

"regexXa*b"

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

because it is a start of "ab" (and "aab")
edit:

由于某些人仍然不理解,因此这里是针对此问题的程序测试:

Since some people still fail to understand, here is a program test for this question:

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 
}
}

结果为真.

推荐答案

您正在寻找的称为 partial matching ,它由Java regex API本地支持(用于记录,其他提供此功能的引擎包括PCRE和boost :: regex).

What you're looking for is called partial matching, and it's natively supported by the Java regex API (for the record, other engines which offer this feature include PCRE and boost::regex).

您可以通过检查

You can tell if an input string matched partially by inspecting the result of the Matcher.hitEnd function, which tells if the match failed because the end of the input string was reached.

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

这将输出:

Matches: false
Partial match: true

这篇关于正则表达式的部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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