我有这个函数,它旨在将字符串作为输入并替换不是字母、数字、下划线或破折号的任何内容: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”代表“单词字符”)。
添加回答
举报
0/150
提交
取消