2016-10-20 67 views
0

我一直在尋找簡單的方法來添加ID到HTML標籤,並花了幾個小時在這裏跳轉形成一個工具到另一個之前,我想出了這個小測試解決我的問題。因此,我的衝刺積壓幾乎是空的,我有一些時間分享。隨意清楚並享受QA要求添加ID的人員。只需更改標籤,路徑並運行:)java替換自動增量文件

由於今天缺乏咖啡而在這裏出現了一些問題,以便製作正確的lambda ... 如何僅在單個lambda中替換第一次發生?在文件中,我有許多行具有相同的標籤。

private void replace(String path, String replace, String replaceWith) { 
    try (Stream<String> lines = Files.lines(Paths.get(path))) { 
     List<String> replaced = lines 
       .map(line -> line.replace(replace, replaceWith)) 
       .collect(Collectors.toList()); 
     Files.write(Paths.get(path), replaced); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

上面是替換所有行,因爲它發現文本要替換下一行。具有自動增量的repleace的適當匹配器將更好地用於此方法體內,而不是在調用之前準備replaceWith值。如果我再次需要這個,我會爲你添加另一個最終版本。

最終版本不會浪費更多的時間(相綠色):

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.mockito.runners.MockitoJUnitRunner; 

import java.io.IOException; 
import java.nio.charset.StandardCharsets; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import java.util.stream.Collectors; 
import java.util.stream.Stream; 

@RunWith(MockitoJUnitRunner.class) 
public class RepalceInFilesWithAutoIncrement { 

    private int incremented = 100; 
    /** 
    * The tag you would like to add Id to 
    * */ 
    private static final String tag = "label"; 
    /** 
    * Regex to find the tag 
    * */ 
    private static final Pattern TAG_REGEX = Pattern.compile("<" + tag + " (.+?)/>", Pattern.DOTALL); 
    private static final Pattern ID_REGEX = Pattern.compile("id=", Pattern.DOTALL); 


    @Test 
    public void replaceInFiles() throws IOException { 

     String nextId = " id=\"" + tag + "_%s\" "; 
     String path = "C:\\YourPath"; 

     try (Stream<Path> paths = Files.walk(Paths.get(path))) { 

      paths.forEach(filePath -> { 
       if (Files.isRegularFile(filePath)) { 

        try { 
         List<String> foundInFiles = getTagValues(readFile(filePath.toAbsolutePath().toString())); 
         if (!foundInFiles.isEmpty()) { 

          for (String tagEl : foundInFiles) { 
           incremented++; 
           String id = String.format(nextId, incremented); 

           String replace = tagEl.split("\\r?\\n")[0]; 
           replace = replace.replace("<" + tag, "<" + tag + id); 


           replace(filePath.toAbsolutePath().toString(), tagEl.split("\\r?\\n")[0], replace, false); 
          } 
         } 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 
     } 
     System.out.println(String.format("Finished with (%s) changes", incremented - 100)); 
    } 

    private String readFile(String path) 
      throws IOException { 
     byte[] encoded = Files.readAllBytes(Paths.get(path)); 
     return new String(encoded, StandardCharsets.UTF_8); 
    } 

    private List<String> getTagValues(final String str) { 
     final List<String> tagValues = new ArrayList<>(); 
     final Matcher matcher = TAG_REGEX.matcher(str); 
     while (matcher.find()) { 
      if (!ID_REGEX.matcher(matcher.group()).find()) 
       tagValues.add(matcher.group()); 
     } 
     return tagValues; 
    } 


    private void replace(String path, String replace, String replaceWith, boolean log) { 
     if (log) { 
      System.out.println("path = [" + path + "], replace = [" + replace + "], replaceWith = [" + replaceWith + "], log = [" + log + "]"); 
     } 

     try (Stream<String> lines = Files.lines(Paths.get(path))) { 
      List<String> replaced = new ArrayList<>(); 
      boolean alreadyReplaced = false; 
      for (String line : lines.collect(Collectors.toList())) { 
       if (line.contains(replace) && !alreadyReplaced) { 
        line = line.replace(replace, replaceWith); 
        alreadyReplaced = true; 
       } 
       replaced.add(line); 
      } 
      Files.write(Paths.get(path), replaced); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

這看起來不像一個問題。請參閱[https://stackoverflow.com/help/self-answer](https://stackoverflow.com/help/self-answer)。 –

+0

totaly同意,而不是一個問題。我在這裏的第一篇文章因此聲譽等於我的智商,因爲有人在早上6點之前醒來,所以我無法回答自己的問題。仍然發現它值得分享,因爲我找不到在文件中搜索和標記修改的好例子。 –

+0

您仍然可以將其重新命名爲問題,並按照鏈接中的建議回答您自己的問題。 –

回答

0

與Jsoup試試吧。

import org.jsoup.Jsoup; 
    import org.jsoup.nodes.Document; 
    import org.jsoup.nodes.Element; 
    import org.jsoup.select.Elements; 

    public class JsoupTest { 

     public static void main(String argv[]) { 

      String html = "<html><head><title>Try it with Jsoup</title></head>" 
          + "<body><p>P first</p><p>P second</p><p>P third</p></body></html>"; 
      Document doc = Jsoup.parse(html);   
      Elements ps = doc.select("p");  // The tag you would like to add Id to 
      int i = 12; 
      for(Element p : ps){ 
       p.attr("id",String.valueOf(i)); 
       i++; 
      } 
      System.out.println(doc.toString()); 
     } 
    }