簡體   English   中英

正則表達式和替換

[英]Regex and replacement

我是Java初學者,上周已經問過類似的問題,但是盡管您的回答很有幫助,但我仍然沒有解決我的問題,因此,我認為我應該為您提供整個故事。 給定一個像

Se excluye arbitraje de ley y [rotura de lunas]Gar_1. Se excluye arbitraje de ley y [rotura de lunas]noGar.

Excluimos todas aquellas cosas que [arbitraje de ley]Gar_1.

Excluimos todas aquellas cosas que son afinidad de [Arbitraje de ley]Gar_1.

我只想為同時具有兩個標簽(在上述示例中為“ [rotura de lunas]”的那些字符串)的字符串標簽“ Gar_1”替換為“ noGar”。 輸入要用來檢查正則表達式以及最終替換位置的句子的輸入是txt文件。

我的代碼如下:

public class Trial_2 {

private static String REGEX = "\\[.*\\](?=(Gar_1|noGar))";  
private static String BE_REPLACED = "Gar_1";  // def part of seq that I want to replace
private static String REPLACE = "noGar";  // def the replacement string     

public static void main(String[] args) throws IOException {

    String input = readFile("corpus_pruebas_multiples_2.txt");
    System.out.println("Original input: " + input);

    Pattern p1 = Pattern.compile(REGEX);  // compare string seq to general pattern 
    Matcher m1 = p1.matcher(input);  // get a matcher object for this general pattern

    if(m1.find( )){
            System.out.println("Found value: " + m1.group(0));  
            Pattern p2 = Pattern.compile(BE_REPLACED);  // compare string to pattern
            Matcher m2 = p2.matcher(input);  // get a matcher object for this pattern
            input = m2.replaceAll(REPLACE);  // replace 
            // print out new string seq with desired replacement:
            System.out.println("Replacement: " + input);  
        } else{
            System.out.println("NO MATCH");
        }     
}


// Method that allows to read from a file by passing it the filename as a param.
      static String readFile(String fileName) throws IOException {

          BufferedReader br = new BufferedReader(new FileReader(fileName));

          try {
              StringBuilder sb = new StringBuilder();
              String line = br.readLine();  

              while(line != null) {
                  sb.append(line);  
                  sb.append("\n");
                  line = br.readLine();  
              }
              return sb.toString(); 
          } finally{
              br.close();
          }
      }
}

我想替換字符串標簽'Gar_1''noGar'只對那些同時具有標簽的字符串(即'[rotura de lunas]'在上述前)。

你可以做:

String repl = str.replaceAll("(?<=\\[rotura de lunas\\])Gar_1", "noGar");

在線演示

編輯:要在方括號中支持各種短語,請使用以下命令:

String repl = str.replaceAll("(?<=\\[(blabla|rotura de lunas)\\])Gar_1", "noGar");

否則,如果要避免替換某些短語,請使用負向后查找:

String repl = str.replaceAll("(\\[(?<!bleble)[^\\]]*\\])Gar_1", "$1noGar");

您可以嘗試使用括號()捕獲的正則表達式的分組功能。 $1代表第一個匹配組。

正則表達式模式: (\\[rotura de lunas\\])(Gar_1)

樣例代碼:

String pattern = "(\\[rotura de lunas\\])(Gar_1)";

String str1 = "Se excluye arbitraje de ley y [rotura de lunas]Gar_1. Se excluye arbitraje de ley y [rotura de lunas]noGar.";
System.out.println(str1.replaceAll(pattern, "$1noGar"));

String str2 = "Excluimos todas aquellas cosas que son afinidad de [Arbitraje de ley]Gar_1.";
System.out.println(str2.replaceAll(pattern, "$1noGar"));

輸出:

Se excluye arbitraje de ley y [rotura de lunas]noGar. Se excluye arbitraje de ley y [rotura de lunas]noGar.
Excluimos todas aquellas cosas que son afinidad de [Arbitraje de ley]Gar_1.

這是regex101上的演示


如果要添加更多內容,只需將其添加到以|分隔的正則表達式模式中即可| 代表OR。

例如

(\[(rotura de lunas)|(blabla)\])(Gar_1)

將與[rotura de lunas]Gar_1[blabla]Gar_1

嘗試這樣的事情。 我基本上所做的就是遍歷輸入,找到\\\\[.*\\\\](?=(Gar_1|noGar))每個出現,然后根據其是否包含Gar_1noGar其粘貼在集合中。 然后,我采用了兩個集合的交集,這樣我就有了一個集合,其中包含被發現兩者均出現的字符串。 然后我只用相同的字符串+ noGar替換了每個字符串+ Gar_1所有noGar

public class Trial_2 {

private static String REGEX = "\\[.*\\](?=(Gar_1|noGar))";  
private static String BE_REPLACED = "Gar_1";  // def part of seq that I want to replace
private static String REPLACE = "noGar";  // def the replacement string     

public static void main(String[] args) throws IOException {

    String input = readFile("corpus_pruebas_multiples_2.txt");
    System.out.println("Original input: " + input);

    Pattern p1 = Pattern.compile(REGEX);  // compare string seq to general pattern 
    Matcher m1 = p1.matcher(input);  // get a matcher object for this general pattern

    Set<String> gar1Set = new HashSet<>();
    Set<String> noGarSet = new HashSet<>();
    while(m1.find( )){
        System.out.println("Found value: " + m1.group());

        String match = m1.group();
        String noLabel = match.substring(0, match.indexOf("]")+1);
        if(match.contains(BE_REPLACED)) {
            gar1Set.add(noLabel);
        }
        else {
            noGarSet.add(noLabel);
        }
    }

    gar1Set.retainAll(noGarSet);
    String replaced = "";
    for(String toReplace : gar1Set) {
        replaced = input.replace(toReplace + BE_REPLACED, toReplace + REPLACE);
    }
    // print out new string seq with desired replacement:
    System.out.println("Replacement: " + replaced);
}


// Method that allows to read from a file by passing it the filename as a param.
      static String readFile(String fileName) throws IOException {

          BufferedReader br = new BufferedReader(new FileReader(fileName));

          try {
              StringBuilder sb = new StringBuilder();
              String line = br.readLine();  

              while(line != null) {
                  sb.append(line);  
                  sb.append("\n");
                  line = br.readLine();  
              }
              return sb.toString(); 
          } finally{
              br.close();
          }
      }
}

注意:我尚未測試過,因此可能存在一些錯誤,但我認為它可以使您理解。

暫無
暫無

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

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