Joh*_*son 4 javascript python regex
我正在尝试接收python并且作为来自Javascript的人我还没有真正理解python的regex包重新
我想做的是我在javascript中做的一些事情来构建一个非常简单的模板"引擎"(我理解AST是一种更复杂的方法):
在javascript中:
var rawString =
"{{prefix_HelloWorld}} testing this. {{_thiswillNotMatch}} \
{{prefix_Okay}}";
rawString.replace(
/\{\{prefix_(.+?)\}\}/g,
function(match, innerCapture){
return "One To Rule All";
});
Run Code Online (Sandbox Code Playgroud)
在Javascript中将导致:
"One To Rule All test this.{{_ thiswillNotMatch}} One To Rule All"
并且函数将被调用两次:
innerCapture === "HelloWorld"
match ==== "{{prefix_HelloWorld}}"
Run Code Online (Sandbox Code Playgroud)
和:
innerCapture === "Okay"
match ==== "{{prefix_Okay}}"
Run Code Online (Sandbox Code Playgroud)
现在,在python中我尝试在re包上查找docs
import re
Run Code Online (Sandbox Code Playgroud)
尝试过做的事情:
match = re.search(r'pattern', string)
if match:
print match.group()
print match.group(1)
Run Code Online (Sandbox Code Playgroud)
但这对我来说真的没有意义,也没有用.首先,我不清楚这个group()概念的含义是什么?我怎么知道是否有match.group(n)... group(n + 11000)?
谢谢!
Python的re.sub功能就像JavaScript一样String.prototype.replace:
import re
def replacer(match):
return match.group(1).upper()
rawString = "{{prefix_HelloWorld}} testing this. {{_thiswillNotMatch}} {{prefix_Okay}}"
result = re.sub(r'\{\{prefix_(.+?)\}\}', replacer, rawString)
Run Code Online (Sandbox Code Playgroud)
结果如下:
'HELLOWORLD testing this. {{_thiswillNotMatch}} OKAY'
Run Code Online (Sandbox Code Playgroud)
至于组,请注意您的替换函数如何接受match参数和innerCapture参数.第一个论点是match.group(0).第二个是match.group(1).