一篇文章带你了解Python和Java的正则表达式对比
程序员文章站
2022-03-09 08:40:18
目录参考资料: java正则表达式实现简单批量替换举例:将and 批量替换为&&python实现import redef transformsimple(fromrege...
参考资料:
简单批量替换
举例:将and
批量替换为&&
python实现
import re def transformsimple(fromregex, totext, intext): return re.sub(fromregex, totext,intext, flags =re.i) if __name__ == "__main__": intext = "x =1 and y =2" fromregex = " and " totext = " && " outtext = transformsimple(fromregex,totext,intext ) print(outtext) ## output: x =1 && y =2
java实现
import java.util.*; import java.util.regex.*; public class regextest { private static string transformsimple(string regexpattern, string repltext, string intext){ return pattern.compile(regexpattern, pattern.case_insensitive).matcher(intext).replaceall(repltext); } public static void main(string[] args) { string input = "x =1 and y =2"; string patternstring =" and "; string totext = " && "; string outtext =""; outtext = transformsimple(patternstring, totext, input); system.out.println("result: " + outtext); } // result: x =1 && y =2
复杂模板替换
举例:将x in (1,2)
批量替换为[1,2].contains(x)
分析: 模板化
- 输入分组捕获
(\s+)\s+in\s*\((.+?)\)
- 输出分组填写
[@2].contains(@1) – @1
和@2分别对应分组捕获中的第1组和2组。
python实现
import re def transformcomplex(fromregex, totext, intext): regobj = re.compile(fromregex, flags =re.i) for match in regobj.finditer(intext): index = 1 outtext = totext for group in match.groups(): outtext = outtext.replace("@"+str(index), group) index +=1 intext = intext.replace(match.group(0), outtext) return intext if __name__ == "__main__": fromregex = "(\s+)\s+in\s*\((.+?)\)" totext = "[@2].contains(@1)" intext = "x in (1,2) and y in (3,4)" outtext22 = transformcomplex(fromregex, totext, intext) print(outtext22) ## output: [1,2].contains(x) and [3,4].contains(y)
java实现
import java.util.*; import java.util.regex.*; public class regextest { private static string transformcomplex(string regexpattern, string repltext, string intext){ pattern pattern = pattern.compile(regexpattern, pattern.case_insensitive); matcher matcher = pattern.matcher(intext); string outtext =""; while (matcher.find()){ outtext = repltext; for (int i =1; i <= matcher.groupcount(); i++){ outtext = outtext.replace("@"+i, matcher.group(i)); } intext = intext.replace(matcher.group(0), outtext); } return intext; } public static void main(string[] args) { string input = "x in (1,2) and y in (3,4)"; string patternstring ="(\\s+)\\s+in\\s*\\((.+?)\\)"; string totext = "[@2].contains(@1)"; string outtext =""; outtext = transformcomplex(patternstring, totext, input); system.out.println("result: " + outtext); } } // result: [1,2].contains(x) and [3,4].contains(y)
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!
上一篇: JavaScript异步编程
下一篇: 深入理解go slice结构