亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用正則表達式在字符串中搜索子字符串

使用正則表達式在字符串中搜索子字符串

MMMHUHU 2022-12-28 14:16:01
我正在嘗試搜索包含在ArrayList(terms_1pers)一個字符串中的一組單詞,并且由于前提是搜索單詞前后不應有字母,我想到了使用正則表達式。我只是不知道我在使用匹配運算符時做錯了什么。在報告的代碼中,如果未驗證匹配,則寫入外部文件。String url = csvRecord.get("url");String text = csvRecord.get("review");String var = null;for(String term : terms_1pers){   if(!text.matches("[^a-z]"+term+"[^a-z]"))   {      var="true";   }}if(!var.equals("true")){    bw.write(url+";"+text+"\n");}
查看完整描述

3 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

為了找到正則表達式匹配項,您應該使用正則表達式類。模式和匹配器。


String term = "term";

ArrayList<String> a  = new ArrayList<String>();

a.add("123term456"); //true

a.add("A123Term5"); //false

a.add("term456"); //true

a.add("123term"); //true

Pattern p = Pattern.compile("^[^A-Za-z]*(" + term + ")[^A-Za-z]*$");

for(String text : a) {

    Matcher m = p.matcher(text);

    if (m.find()) {

         System.out.println("Found: " + m.group(1) );

         //since the term you are adding is the second matchable portion, you're looking for group(1)

    }

    else System.out.println("No match for: " + term);

}

}


在那里的示例中,我們創建了一個https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html的實例,以在您匹配的文本中查找匹配項。


請注意,我稍微調整了正則表達式。此代碼中的選擇從初始匹配部分中排除了所有字母 AZ 和小寫版本。它還將允許在匹配項之前或之后根本沒有字符的情況。如果您需要在那里放置一些東西,請使用+而不是*. ^我還通過使用和$驗證匹配文本的結尾來限制正則表達式以強制匹配僅包含這三個組的匹配項。如果這不適合您的用例,您可能需要進行調整。


為了演示如何使用各種不同的術語:


ArrayList<String> terms = new ArrayList<String>();

terms.add("term");

terms.add("the book is on the table");

terms.add("1981 was the best year ever!");

ArrayList<String> a  = new ArrayList<String>();

a.add("123term456");

a.add("A123Term5");

a.add("the book is on the table456");

a.add("1@#!231981 was the best year ever!9#");

for (String term: terms) {


    Pattern p = Pattern.compile("^[^A-Za-z]*(" + term + ")[^A-Za-z]*$");


    for(String text : a) {


        Matcher m = p.matcher(text);

        if (m.find()) {

             System.out.println("Found: " + m.group(1)  + " in " + text);

             //since the term you are adding is the second matchable portion, you're looking for group(1)

        }

        else System.out.println("No match for: " + term + " in " + text);

    }

}

此輸出為:找到:123term456 中的術語不匹配:A123Term5 中的術語不匹配:書中的術語在 table456 上....


為了回答有關讓字符串項不區分大小寫的問題,這里有一種方法可以通過利用java.lang.Character大寫和小寫字母的選項來構建字符串。


String term = "This iS the teRm.";

String matchText = "123This is the term.";

StringBuilder str = new StringBuilder();

str.append("^[^A-Za-z]*(");

for (int i = 0; i < term.length(); i++) {

  char c = term.charAt(i);

  if (Character.isLetter(c))

    str.append("(" + Character.toLowerCase(c) + "|" + Character.toUpperCase(c) + ")");

  else str.append(c);

}

str.append(")[^A-Za-z]*$");


System.out.println(str.toString());



Pattern p = Pattern.compile(str.toString());

Matcher m = p.matcher(matchText);

if (m.find()) System.out.println("Found!");

else System.out.println("Not Found!");

此代碼輸出兩行,第一行是在模式中編譯的正則表達式字符串。"^[^A-Za-z]*((t|T)(h|H)(i|I)(s|S) (i|I)(s|S) (t|T)(h|H)(e|E) (t|T)(e|E)(r|R)(m|M).)[^A-Za-z]*$"這個調整后的正則表達式允許匹配術語中的字母而不考慮大小寫。第二行輸出是“Found!” 因為混合大小寫術語在 matchText 中找到。


查看完整回答
反對 回復 2022-12-28
?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

有幾點需要注意:

  • matches需要完整的字符串匹配,因此[^a-z]term[^a-z]只會匹配像:term.. 您需要使用.find()來查找部分匹配項

  • 如果將文字字符串傳遞給正則表達式,則需要Pattern.quote它,或者如果它包含特殊字符,則不會匹配

  • 要檢查單詞之前或之后在開始/結束時是否有某種模式,您應該使用帶有錨點的交替(如(?:^|[^a-z])or (?:$|[^a-z]))或 lookarounds(?<![a-z])(?![a-z])。

  • 要匹配任何字母,只需使用\p{Alpha}or - 如果您打算匹配任何 Unicode 字母 - \p{L}。

  • var變量設置為布爾類型更符合邏輯。

固定代碼:

String url = csvRecord.get("url");

String text = csvRecord.get("review");

Boolean var = false;

for(String term : terms_1pers)

{

   Matcher m = Pattern.compile("(?<!\\p{L})" + Pattern.quote(term) + "(?!\\p{L})").matcher(text);

   // If the search must be case insensitive use

   // Matcher m = Pattern.compile("(?i)(?<!\\p{L})" + Pattern.quote(term) + "(?!\\p{L})").matcher(text); 

   if(!m.find())

   {

       var = true;

   }

}

if (!var) {

   bw.write(url+";"+text+"\n");

}


查看完整回答
反對 回復 2022-12-28
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

您沒有考慮開頭和結尾可能包含字母的情況,因此在開頭和結尾添加 .* 應該可以解決您的問題。


for(String term : terms_1pers)

{

   if( text.matches(".*[^a-zA-Z]+" + term + "[^a-zA-Z]+.*)" )  

   {

      var="true";

      break; //exit the loop

   }

}

if(!var.equals("true"))

{

    bw.write(url+";"+text+"\n");

}


查看完整回答
反對 回復 2022-12-28
  • 3 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號