这篇文章主要讲解了“Python和Java的正则表达式对比”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python和Java的正则表达式对比”吧!
简单批量替换
复杂模板替换
总结
举例:将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)
感谢各位的阅读,以上就是“Python和Java的正则表达式对比”的内容了,经过本文的学习后,相信大家对Python和Java的正则表达式对比这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。