为了账号安全,请及时绑定邮箱和手机立即绑定

regex 替换除小写字母、数字字符、下划线和破折号之外的所有内容

regex 替换除小写字母、数字字符、下划线和破折号之外的所有内容

万千封印 2021-07-15 17:11:13
我有这个函数,它旨在将字符串作为输入并替换不是字母、数字、下划线或破折号的任何内容:def clean_label_value(label_value):    """    GCP Label values have to follow strict guidelines        Keys and values can only contain lowercase letters, numeric characters, underscores,        and dashes. International characters are allowed.    https://cloud.google.com/compute/docs/labeling-resources#restrictions    :param label_value: label value that needs to be cleaned up    :return: cleaned label value    """    full_pattern = re.compile('[^a-zA-Z0-9]')    return re.sub(full_pattern, '_', label_value).lower()我有这个单元测试,它成功了def test_clean_label_value(self):    self.assertEqual(clean_label_value('XYZ_@:.;\\/,'), 'xyz________')但是它替换了破折号,我不希望它这样做。展示:def clean_label_value(label_value):    full_pattern = re.compile('[^a-zA-Z0-9]|-')    return re.sub(full_pattern, '_', label_value).lower()但是这个:def test_clean_label_value(self):    self.assertEqual(clean_label_value('XYZ-'), 'xyz-')然后失败了xyz- != xyz_预期:xyz_实际:xyz-换句话说,-正在被替换为_。我不希望这种情况发生。我摆弄了正则表达式,尝试了各种不同的组合,但我无法弄清楚该死的事情。任何人?
查看完整描述

1 回答

?
弑天下

TA贡献1818条经验 获得超8个赞

-在集合的开头或结尾放置一个单曲(字符类)。然后它不会创建字符范围,而是代表文字-字符本身。

re.compile('[^-a-zA-Z0-9]')

也可以-使用 a转义\, 以指示它是一个文字破折号字符而不是集合内的范围运算符。

re.compile(r'[^\-\w]')

特殊序列\w等价于集合[a-zA-Z0-9_](“w”代表“单词字符”)。


查看完整回答
反对 回复 2021-07-21
  • 1 回答
  • 0 关注
  • 237 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号