您好,登錄后才能下訂單哦!
這篇文章主要講解了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。