簡體   English   中英

正則表達式的部分匹配

[英]Partial Matching of Regular Expressions

在NFA中,很容易使所有先前非最終狀態接受使其匹配給定語言的所有子串的語言。

在Java regex引擎中,有沒有辦法找出字符串是否是與給定正則表達式匹配的字符串的起始子字符串?

regexX =“任何開始”,regexA - 任何給定的正則表達式

“regexXregexA”結果表達式匹配匹配“regexA”的所有子字符串:

例:

regexA = a*b

“a”匹配

"regexXa*b"

因為它是“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 
}
}

結果是真的。

您正在尋找的是部分匹配 ,它由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());

這輸出:

Matches: false
Partial match: true

在NFA中,很容易使所有先前非最終狀態接受使其匹配給定語言的所有子串的語言。

實際上,它可以通過添加新的最終狀態和從每個狀態(最終或非最終)到新的最終狀態的ε-移動來實現。

Afaik沒有與此操作等效的正則表達式。

有些正則表達式庫可能提供一種方法來驗證字符串是否是正則表達式的部分匹配,我不知道。 我不懂Java,我主要在PHP工作,它沒有提供這樣的功能。 也許有圖書館這樣做,但我從來不需要一個。

對於一個小的,特定的正則表達式,您可以嘗試通過組合這些簡單的規則來構建一個匹配與原始正則表達式部分匹配的字符串的新正則表達式:

  • a - > a?
  • ab - > ab?
  • a* - > a*
  • a+ - > a*
  • a|b - > (a|b)?
  • 等等

上面的ab是原始正則表達式的子正則表達式。 根據需要使用括號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM