2010-06-15 48 views

Trả lời

4

Vâng mã nguồn của Pattern.quote có sẵn và trông như thế này:

public static String quote(String s) { 
    int slashEIndex = s.indexOf("\\E"); 
    if (slashEIndex == -1) 
     return "\\Q" + s + "\\E"; 

    StringBuilder sb = new StringBuilder(s.length() * 2); 
    sb.append("\\Q"); 
    slashEIndex = 0; 
    int current = 0; 
    while ((slashEIndex = s.indexOf("\\E", current)) != -1) { 
     sb.append(s.substring(current, slashEIndex)); 
     current = slashEIndex + 2; 
     sb.append("\\E\\\\E\\Q"); 
    } 
    sb.append(s.substring(current, s.length())); 
    sb.append("\\E"); 
    return sb.toString(); 
} 

Về cơ bản nó dựa trên

\Q Nothing, but quotes all characters until \E 
\E Nothing, but ends quoting started by \Q 

và có một treatement đặc biệt của vụ án trong đó \E hiện diện trong chuỗi.

+0

Đó sẽ thực sự làm cho tôi. Xin lỗi, nhưng làm thế nào bạn có được nguồn gốc? – AHungerArtist

+1

Nguồn được cung cấp cùng với SDK, trong nhật thực bạn có thể chuyển đổi-klick trên một lớp để xem nguồn của nó. –

+0

Có sẵn để tải xuống tại http://java.sun.com/javase/downloads/index.jsp – aioobe

2

Đây là mã của quote:

public static String quote(String s) { 
     int slashEIndex = s.indexOf("\\E"); 
     if (slashEIndex == -1) 
      return "\\Q" + s + "\\E"; 

     StringBuilder sb = new StringBuilder(s.length() * 2); 
     sb.append("\\Q"); 
     slashEIndex = 0; 
     int current = 0; 
     while ((slashEIndex = s.indexOf("\\E", current)) != -1) { 
      sb.append(s.substring(current, slashEIndex)); 
      current = slashEIndex + 2; 
      sb.append("\\E\\\\E\\Q"); 
     } 
     sb.append(s.substring(current, s.length())); 
     sb.append("\\E"); 
     return sb.toString(); 
    } 

vẻ không sao chép cứng hoặc thực hiện bằng cách tự mình hoặc?

Edit: aiobee là nhanh hơn, sry

+1

Bạn có thể thêm giá trị cho câu trả lời của mình bằng cách thay thế StringBuilder bằng StringBuffer; StringBuilder không được giới thiệu cho đến JDK 1.5. –

1

Đây là việc thực hiện GNU Classpath (trong trường hợp giấy phép Java lo lắng bạn):

public static String quote(String str) 
    { 
    int eInd = str.indexOf("\\E"); 
    if (eInd < 0) 
     { 
     // No need to handle backslashes. 
     return "\\Q" + str + "\\E"; 
     } 

    StringBuilder sb = new StringBuilder(str.length() + 16); 
    sb.append("\\Q"); // start quote 

    int pos = 0; 
    do 
     { 
     // A backslash is quoted by another backslash; 
     // 'E' is not needed to be quoted. 
     sb.append(str.substring(pos, eInd)) 
      .append("\\E" + "\\\\" + "E" + "\\Q"); 
     pos = eInd + 2; 
     } while ((eInd = str.indexOf("\\E", pos)) >= 0); 

    sb.append(str.substring(pos, str.length())) 
     .append("\\E"); // end quote 
    return sb.toString(); 
    } 
Các vấn đề liên quan