String 교체 작업 에 대한 약간의 노트

5865 단어 자바String정칙
최근 프로젝트 는 학교 백합 의 핫 이 슈 정 보 를 캡 처 해 야 합 니 다.정규 와 String 의 일부 교체 작업 을 자주 사용 하 는 것 을 피 할 수 없습니다.문제 가 생 겼 으 니 적 을 필요 가 있 습 니 다.
다음은 조작 한 세 션 입 니 다.
Pattern textareaContent = Pattern.compile("(?s)(<table)(.*?)<textarea.*?class=hide>(.*?)</textarea>");
Matcher contentMatcher = textareaContent.matcher(resultHTML);
		StringBuffer buff = new StringBuffer();
		while(contentMatcher.find()) {
			contentMatcher.appendReplacement(buff, contentMatcher.group(1) + " style='BORDER: 2px solid;BORDER-COLOR: D0F0C0;' "
					+ contentMatcher.group(2) + contentMatcher.group(3));
		}
		resultHTML = contentMatcher.appendTail(buff).toString();

캡 처 한 내용 에'$','\\'등의 문자 가 있 을 수 있 기 때문에 appendReplacement(StringBuffer,String replacement)에서 오류 가 발생 할 수 있 습 니 다.예 를 들 어$replace 에서 group 의 선택 기로 사용 할 수 있 습 니 다.사실은 jdk 의 소스 코드 를 통 해 appendRelacement 의 처리 방식 을 명확 하 게 볼 수 있 습 니 다.
char nextChar = replacement.charAt(cursor);
            if (nextChar == '\\') {//   '\\'      nextChar  buffer
                cursor++;
                nextChar = replacement.charAt(cursor);
                result.append(nextChar);
                cursor++;
            } else if (nextChar == '$') {//    '$' ,  nextChar      
                // Skip past $   '$'!!!!!
                cursor++;
                // A StringIndexOutOfBoundsException is thrown if
                // this "$" is the last character in replacement
                // string in current implementation, a IAE might be
                // more appropriate.
                nextChar = replacement.charAt(cursor);
                int refNum = -1;
                if (nextChar == '{') {
                    cursor++;//  '{'
                    StringBuilder gsb = new StringBuilder();
                    while (cursor < replacement.length()) {// '{'         
                        nextChar = replacement.charAt(cursor);
                        if (ASCII.isLower(nextChar) ||
                            ASCII.isUpper(nextChar) ||
                            ASCII.isDigit(nextChar)) {
                            gsb.append(nextChar);
                            cursor++;
                        } else {
                            break;
                        }
                    }
                    if (gsb.length() == 0)//  buffer      
                        throw new IllegalArgumentException(
                            "named capturing group has 0 length name");
                    if (nextChar != '}')
                        throw new IllegalArgumentException(
                            "named capturing group is missing trailing '}'");
                    String gname = gsb.toString();
                    if (ASCII.isDigit(gname.charAt(0)))//          
                        throw new IllegalArgumentException(
                            "capturing group name {" + gname +
                            "} starts with digit character");
                    if (!parentPattern.namedGroups().containsKey(gname))// pattern    
                        throw new IllegalArgumentException(
                            "No group with name {" + gname + "}");
                    refNum = parentPattern.namedGroups().get(gname);
                    cursor++;
                } else {//            char     
                    // The first number is always a group
                    refNum = (int)nextChar - '0';
                    if ((refNum < 0)||(refNum > 9))
                        throw new IllegalArgumentException(
                            "Illegal group reference");
                    cursor++;
                    // Capture the largest legal group string
                    boolean done = false;
                    while (!done) {
                        if (cursor >= replacement.length()) {
                            break;
                        }
                        int nextDigit = replacement.charAt(cursor) - '0';
                        if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
                            break;
                        }
                        int newRefNum = (refNum * 10) + nextDigit;
                        if (groupCount() < newRefNum) {
                            done = true;
                        } else {
                            refNum = newRefNum;
                            cursor++;
                        }
                    }
                }
                // Append group
                if (start(refNum) != -1 && end(refNum) != -1)
                    result.append(text, start(refNum), end(refNum));
            } 

처리 방법:Matcher.quoteReplacement()
if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
            return s;
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            if (c == '\\' || c == '$') {
                sb.append('\\');
            }
            sb.append(c);
        }
        return sb.toString();

특수 글자 앞 에'\\'삽입 하기;
그리고 String.replace()
public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }

Matcher.replace All 을 통 해 이 루어 졌 습 니 다.

좋은 웹페이지 즐겨찾기