gpt4 book ai didi

java - 正则表达式的部分匹配

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:52 24 4
gpt4 key购买 nike

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

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

expression regexX ~ "any start of", regexA = any normal regex

结果表达式“regexXregexA”匹配“regexA”所有匹配项的所有起始子串:

例子:

regexA = a*b, matches "ab" and not "a"

"regexXa*b", matches "a" because it is a start of "ab" (and "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
}
}

结果必须为真。

最佳答案

您正在寻找的称为部分匹配,它由 Java regex 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());

这个输出:

Matches: false
Partial match: true

关于java - 正则表达式的部分匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42073491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com