1

有没有办法修改反向引用的值?

示例:在以下文本中

"this is a test"

应该通过反向引用提取单词“test”并插入到另一个文本中。

正则表达式:

(test)

替代品:

"this is another \1"

到目前为止效果很好。但现在的问题是,是否可以在插入之前修改反向引用。类似于将单词“test”转换为大写。

我认为它可能看起来像:

"this is another \to_upper\1"

正则表达式的“标准”(是否有任何标准?)中是否有定义?

4

1 回答 1

5

许多实现(javascript、python 等)允许您将函数指定为替换参数。该函数通常将整个匹配的字符串、它在输入字符串中的位置以及捕获的组作为参数。此函数返回的字符串用作替换文本。

下面是使用 JavaScript 的方法:replace 函数将整个匹配的子字符串作为其第一个参数,捕获的组的值作为接下来的 n 个参数,然后是原始输入字符串和整个输入字符串中匹配字符串的索引.

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.

这是 python 版本 - 它甚至为您提供每个组的开始/结束值:

#!/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.
于 2010-07-30T09:18:55.933 回答