编译用户输入
我假设用户输入是一个字符串,无论它来自您的系统:user_input = input("Input regex:") # check console, it is expecting your input
print("User typed: '{}'. Input type: {}.".format(user_input, type(user_input)))
这意味着您需要将其转换为regex,这就是re.compile的用途。如果使用re.compile并且没有提供有效的str来转换为regex,它将抛出一个错误。
因此,您可以创建一个函数来检查输入是否有效。您使用了re.escape,所以我在函数中添加了一个标志来使用re.escape。
^{pr2}$
如果您的用户输入是:\t+,您将得到:>> If you don't use re.escape, the input is valid: True.
>> If you do use re.escape, the input is valid: True.
但是,如果您的用户输入是:[\t+,您将得到:>> If you don't use re.escape, the input is valid: False.
>> If you do use re.escape, the input is valid: True.
注意,它确实是一个无效的regex,但是,通过使用re.escape您的regex就变得有效了。这是因为re.escape转义了所有的特殊字符,将它们视为字面字符。所以在你有\t+的情况下,如果你使用re.escape,你将寻找一个字符序列:\,t,+,而不是tab character。
正在检查查找字符串
把你想看的绳子拿出来。
例如,这里有一个字符串,其中引号之间的字符应该是制表符:string_to_look_in = 'This is a string with a " " tab character.'
您可以使用repr函数手动检查选项卡。print(string_to_look_in)
print(repr(string_to_look_in))>> This is a string with a " " tab character.
>> 'This is a string with a "\t" tab character.'
注意,通过使用repr来显示制表符的\t表示。
测试脚本
下面是一个脚本,供您尝试所有这些事情:import re
string_to_look_in = 'This is a string with a " " tab character.'
print("String to look into:", string_to_look_in)
print("String to look into:", repr(string_to_look_in), "\n")
user_input = input("Input regex:") # check console, it is expecting your input
print("\nUser typed: '{}'. Input type: {}.".format(user_input, type(user_input)))
def is_valid_regex(regex_from_user: str, escape: bool) -> bool:
try:
if escape: re.compile(re.escape(regex_from_user))
else: re.compile(regex_from_user)
is_valid = True
except re.error:
is_valid = False
return is_valid
print("\nIf you don't use re.escape, the input is valid: {}.".format(is_valid_regex(user_input, escape=False)))
print("If you do use re.escape, the input is valid: {}.".format(is_valid_regex(user_input, escape=True)))
if is_valid_regex(user_input, escape=False):
regex = re.compile(user_input)
print("\nRegex compiled as '{}' with type {}.".format(repr(regex), type(regex)))
matches = regex. findall(string_to_look_in)
print('Mathces found:', matches)
else:
print('\nThe regex was not valid, so no matches.')