You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
1.7 KiB
79 lines
1.7 KiB
7 years ago
|
try:
|
||
2 years ago
|
import re
|
||
7 years ago
|
except ImportError:
|
||
2 years ago
|
print("SKIP")
|
||
|
raise SystemExit
|
||
7 years ago
|
|
||
|
try:
|
||
|
re.sub
|
||
|
except AttributeError:
|
||
5 years ago
|
print("SKIP")
|
||
7 years ago
|
raise SystemExit
|
||
|
|
||
|
|
||
|
def multiply(m):
|
||
|
return str(int(m.group(0)) * 2)
|
||
|
|
||
5 years ago
|
|
||
7 years ago
|
print(re.sub("\d+", multiply, "10 20 30 40 50"))
|
||
|
|
||
|
print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50"))
|
||
|
|
||
5 years ago
|
|
||
7 years ago
|
def A():
|
||
|
return "A"
|
||
5 years ago
|
|
||
|
|
||
|
print(re.sub("a", A(), "aBCBABCDabcda."))
|
||
7 years ago
|
|
||
|
print(
|
||
|
re.sub(
|
||
5 years ago
|
r"def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):",
|
||
|
"static PyObject*\npy_\\1(void){\n return;\n}\n",
|
||
|
"\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():",
|
||
7 years ago
|
)
|
||
5 years ago
|
)
|
||
7 years ago
|
|
||
|
print(
|
||
5 years ago
|
re.compile("(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)").sub(
|
||
|
r"\g<1> colore \2 con \g<3> colore \4? ...", "calzino blu e scarpa verde"
|
||
7 years ago
|
)
|
||
|
)
|
||
|
|
||
4 years ago
|
# \g immediately followed by another \g
|
||
|
print(re.sub("(abc)", r"\g<1>\g<1>", "abc"))
|
||
|
|
||
7 years ago
|
# no matches at all
|
||
5 years ago
|
print(re.sub("a", "b", "c"))
|
||
7 years ago
|
|
||
|
# with maximum substitution count specified
|
||
5 years ago
|
print(re.sub("a", "b", "1a2a3a", 2))
|
||
7 years ago
|
|
||
|
# invalid group
|
||
|
try:
|
||
5 years ago
|
re.sub("(a)", "b\\2", "a")
|
||
7 years ago
|
except:
|
||
5 years ago
|
print("invalid group")
|
||
7 years ago
|
|
||
|
# invalid group with very large number (to test overflow in uPy)
|
||
|
try:
|
||
5 years ago
|
re.sub("(a)", "b\\199999999999999999999999999999999999999", "a")
|
||
7 years ago
|
except:
|
||
5 years ago
|
print("invalid group")
|
||
4 years ago
|
|
||
|
# Module function takes str/bytes/re.
|
||
|
print(re.sub("a", "a", "a"))
|
||
|
print(re.sub(b".", b"a", b"a"))
|
||
|
print(re.sub(re.compile("a"), "a", "a"))
|
||
|
try:
|
||
|
re.sub(123, "a", "a")
|
||
|
except TypeError:
|
||
|
print("TypeError")
|
||
4 years ago
|
|
||
|
# Include \ in the sub replacement
|
||
|
print(re.sub("b", "\\\\b", "abc"))
|
||
3 years ago
|
|
||
|
# Using ^, make sure it doesn't repeatedly match
|
||
|
print(re.sub("^ab", "*", "abababcabab"))
|
||
|
print(re.sub("^ab|cab", "*", "abababcabab"))
|