python正则表达式思考_Python用户输入作为正则表达式,如何正确做呢?

编译用户输入

我假设用户输入是一个字符串,无论它来自您的系统: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.')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值