많은 구현 (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.
표준 가능성은 매우 낮지 만 구현에 따라서는 다음과 같이 할 수 있습니다 :'$ echo testx | perl -pe 's/(test)/\ U \ 1 /''->'TESTx' – mykhal
많은 구현 (javascript, python 등)을 사용하면 replace 매개 변수로 함수를 지정할 수 있습니다. 함수는 일반적으로 일치하는 문자열과 캡처 된 그룹을 인수로 사용하고 반환 값은 대체 텍스트로 사용됩니다. – Amarghosh
@Amarghosh : 답변으로 게시하고 샘플 코드를 추가 할 수도 있습니다. –