2010-07-30 5 views
1

역 참조의 값을 수정할 수있는 방법이 있습니까?RegEx 수정 역 참조의 값

예 : 다음 텍스트

"this is a test" 

단어 "시험 '추출 backrefrence 통해 다른 텍스트에 삽입해야에서 .

정규식 :

(test) 

교체 : 지금까지 잘 작동

"this is another \1" 

. 그러나 삽입하기 전에 역 참조를 수정할 수 있다면 문제가됩니다. "test"라는 단어를 대문자로 변환하는 것과 같은 것입니다. (표준이 전혀 존재?) 정규 표현식의

"this is another \to_upper\1" 

은 "표준"에 정의 된 무언가가 있는가 :

나는 그 모습 수 있다고 생각?

+2

표준 가능성은 매우 낮지 만 구현에 따라서는 다음과 같이 할 수 있습니다 :'$ echo testx | perl -pe 's/(test)/\ U \ 1 /''->'TESTx' – mykhal

+2

많은 구현 (javascript, python 등)을 사용하면 replace 매개 변수로 함수를 지정할 수 있습니다. 함수는 일반적으로 일치하는 문자열과 캡처 된 그룹을 인수로 사용하고 반환 값은 대체 텍스트로 사용됩니다. – Amarghosh

+0

@Amarghosh : 답변으로 게시하고 샘플 코드를 추가 할 수도 있습니다. –

답변

4

많은 구현 (javascript, python 등)을 사용하면 replace 매개 변수로 함수를 지정할 수 있습니다. 함수는 일반적으로 일치하는 전체 문자열, 입력 문자열에서의 위치 및 캡처 된 그룹을 인수로 취합니다. 이 함수가 반환 한 문자열이 대체 텍스트로 사용됩니다.

JavaScript를 사용하여 수행하는 방법은 다음과 같습니다. replace 함수는 첫 번째 인수로 전체 일치 부분 문자열을 가져오고, 다음 n 인수로 캡처 된 그룹 값을 취하고 원래 입력 문자열에서 일치 문자열의 인덱스를 취하고 전체 입력 문자열 OUPUT

var s = "this is a test. and this is another one."; 
console.log("replacing"); 
r = s.replace(/(this is) ([^.]+)/g, function(match, first, second, pos, input) { 
    console.log("matched :" + match); 
    console.log("1st group :" + first); 
    console.log("2nd group :" + second); 
    console.log("position :" + pos); 
    console.log("input  :" + input); 
    return "That is " + second.toUpperCase(); 
}); 
console.log("replaced string is"); 
console.log(r); 

: 여기

replacing 
matched :this is a test 
1st group :this is 
2nd group :a test 
pos  :0 
input  :this is a test. and this is another one. 
matched :this is another one 
1st group :this is 
2nd group :another one 
pos  :20 
input  :this is a test. and this is another one. 
replaced string is 
That is A TEST. and That is ANOTHER ONE. 

그리고는 파이썬 버전입니다 - 그것은 심지어 당신이 각 그룹에 대해/종료 값을 시작 제공합니다

#!/usr/bin/python 
import re 
s = "this is a test. and this is another one."; 
print("replacing"); 

def repl(match): 
    print "matched :%s" %(match.string[match.start():match.end()]) 
    print "1st group :%s" %(match.group(1)) 
    print "2nd group :%s" %(match.group(2)) 
    print "position :%d %d %d" %(match.start(), match.start(1), match.start(2)) 
    print "input  :%s" %(match.string) 
    return "That is %s" %(match.group(2).upper()) 

print "replaced string is \n%s"%(re.sub(r"(this is) ([^.]+)", repl, s)) 

출력 :

replacing 
matched :this is a test 
1st group :this is 
2nd group :a test 
position :0 0 8 
input  :this is a test. and this is another one. 
matched :this is another one 
1st group :this is 
2nd group :another one 
position :20 20 28 
input  :this is a test. and this is another one. 
replaced string is 
That is A TEST. and That is ANOTHER ONE.