簡體   English   中英

Java正則表達式匹配單詞的開頭嗎?

[英]Java regex to match the start of the word?

目標 :對於給定的術語,我想檢查該術語是否在單詞開頭。 例如,如果術語為“ t”。 然后在情感上:

“這是困難的,就是這樣”

我希望它返回“ true ”,原因是:

這,那,那

因此請考慮:

public class HelloWorld{

 public static void main(String []args){

    String term = "t";
    String regex = "/\\b"+term+"[^\\b]*?\\b/gi";
    String str = "This is the difficult one Thats it";
    System.out.println(str.matches(regex));

 }
}

我得到以下異常

Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal/unsupported escape sequence near index 7                                         
/\bt[^\b]*?\b/gi                                                              
       ^                                                                      
        at java.util.regex.Pattern.error(Pattern.java:1924)                   
        at java.util.regex.Pattern.escape(Pattern.java:2416)                  
        at java.util.regex.Pattern.range(Pattern.java:2577)                   
        at java.util.regex.Pattern.clazz(Pattern.java:2507)                   
        at java.util.regex.Pattern.sequence(Pattern.java:2030)                
        at java.util.regex.Pattern.expr(Pattern.java:1964)                    
        at java.util.regex.Pattern.compile(Pattern.java:1665)                 
        at java.util.regex.Pattern.<init>(Pattern.java:1337)                  
        at java.util.regex.Pattern.compile(Pattern.java:1022)                 
        at java.util.regex.Pattern.matches(Pattern.java:1128)                 
        at java.lang.String.matches(String.java:2063)                         
        at HelloWorld.main(HelloWorld.java:8)

同樣,以下內容不起作用:

import java.util.regex.*;
public class HelloWorld{

 public static void main(String []args){

    String term = "t";
    String regex = "\\b"+term+"gi";
    //String regex = ".";
    System.out.println(regex);
    String str = "This is the difficult one Thats it";
    System.out.println(str.matches(regex));


     Pattern p = Pattern.compile(regex);
     Matcher m = p.matcher(str);
     System.out.println(m.find());
 }
}

示例:{This,one,Two,That,thank}表示This Two That Thanks; 結果應該是真的。

謝謝

由於您使用的是Java regex引擎,因此需要以Java能夠理解的方式編寫表達式。 這意味着刪除尾部和前導斜杠,並在表達式的開頭添加標記為(?<flags>)

因此,您需要使用它:

String regex = "(?i)\\b"+term+".*?\\b"

請查看regular-expressions.info/java.html以獲取更多信息。 可以在此處找到支持功能的比較(僅作為切入點): regular-expressions.info/refbasic.html

在Java中,我們不使用/包圍正則表達式,因此我們只寫regex而不是"/regex/flags" 如果要添加標志,則可以使用(?flags)語法來完成,然后將其放在要應用標志的位置的regex中,例如a(?i)a將能夠找到aaaA但不能找到Aa因為標志在第a之后添加。
您也可以像這樣將正則表達式編譯為Pattern

Pattern pattern = Pattern.compile(regex, flags);

其中regex是String(同樣也不用/括起來),而flag是從Pattern.DOTALL Pattern中的常量生成的整數,或者當您需要更多標志時,可以使用Pattern.CASE_INSENSITIVE|Pattern.MULTILINE

可能使您感到困惑的下一件事是matches方法。 大多數人會誤以為它的名稱,因為他們認為它會嘗試檢查它是否可以在正則表達式可以匹配的字符串元素中find ,但實際上,它會檢查整個字符串是否可以被正則表達式匹配。

您似乎想要的是某種正則表達式的測試機制可以在字符串中至少找到一次。 在這種情況下,您可以

  • 在正則表達式的開頭和結尾添加.* ,以使正則表達式引擎可以匹配不屬於您要查找的元素的其他字符,但是這種matches必須遍歷整個字符串
  • 使用Pattern Matcher對象構建(代表您的正則表達式),並使用其find()方法,該方法將迭代直到找到與正則表達式匹配的對象,或者找到字符串的結尾。 我更喜歡這種方法,因為它不需要遍歷整個字符串,但是會在找到匹配項時停止。

所以你的代碼看起來像

String str = "This is the difficult one Thats it";
String term = "t";
Pattern pattern = Pattern.compile("\\b"+term, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.find());

如果您的term可能包含一些正則表達式特殊字符,但是您希望正則表達式引擎將它們視為普通字符,則需要確保將其轉義。 為此,您可以使用Pattern.quote方法,該方法將為您添加所有必需的轉義符,因此,

Pattern pattern = Pattern.compile("\\b"+term, Pattern.CASE_INSENSITIVE);

為了安全起見,您應該使用

Pattern pattern = Pattern.compile("\\b"+Pattern.quote(term), Pattern.CASE_INSENSITIVE);
String regex = "(?i)\\b"+term;

在Java中,修飾符必須插入在“(?”和“)”之間,並且有一個變種可以再次將其關閉:“(?-”和“)”。

為了查找所有以“ T”或“ t”開頭的單詞,您可能需要重復使用Matcher的find方法。 如果只需要偏移量,則Matcher的start方法將返回偏移量。

如果您需要匹配整個單詞,請使用

 String regex = "(?i)\\b"+term + "\\w*";
    String str = "This is the difficult one Thats it";
    String term = "t";
    Pattern pattern = Pattern.compile("^[+"+term+"].*",Pattern.CASE_INSENSITIVE);

    String[] strings = str.split(" ");
    for (String s : strings) {
        if (pattern.matcher(s).matches()) {
            System.out.println(s+"-->"+true);
        } else {
            System.out.println(s+"-->"+false);
        }
    }

暫無
暫無

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

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