1try: 2 import ure as re 3except ImportError: 4 try: 5 import re 6 except ImportError: 7 print("SKIP") 8 raise SystemExit 9 10try: 11 re.sub 12except AttributeError: 13 print("SKIP") 14 raise SystemExit 15 16 17def multiply(m): 18 return str(int(m.group(0)) * 2) 19 20 21print(re.sub("\d+", multiply, "10 20 30 40 50")) 22 23print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50")) 24 25 26def A(): 27 return "A" 28 29 30print(re.sub("a", A(), "aBCBABCDabcda.")) 31 32print( 33 re.sub( 34 r"def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):", 35 "static PyObject*\npy_\\1(void){\n return;\n}\n", 36 "\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():", 37 ) 38) 39 40print( 41 re.compile("(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)").sub( 42 r"\g<1> colore \2 con \g<3> colore \4? ...", "calzino blu e scarpa verde" 43 ) 44) 45 46# \g immediately followed by another \g 47print(re.sub("(abc)", r"\g<1>\g<1>", "abc")) 48 49# no matches at all 50print(re.sub("a", "b", "c")) 51 52# with maximum substitution count specified 53print(re.sub("a", "b", "1a2a3a", 2)) 54 55# invalid group 56try: 57 re.sub("(a)", "b\\2", "a") 58except: 59 print("invalid group") 60 61# invalid group with very large number (to test overflow in uPy) 62try: 63 re.sub("(a)", "b\\199999999999999999999999999999999999999", "a") 64except: 65 print("invalid group") 66 67# Module function takes str/bytes/re. 68print(re.sub("a", "a", "a")) 69print(re.sub(b".", b"a", b"a")) 70print(re.sub(re.compile("a"), "a", "a")) 71try: 72 re.sub(123, "a", "a") 73except TypeError: 74 print("TypeError") 75 76# Include \ in the sub replacement 77print(re.sub("b", "\\\\b", "abc")) 78