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

我有这个函数,它旨在将字符串作为输入并替换不是字母、数字、下划线或破折号的任何内容:


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-


换句话说,-正在被替换为_。我不希望这种情况发生。我摆弄了正则表达式,尝试了各种不同的组合,但我无法弄清楚该死的事情。任何人?


万千封印
浏览 238回答 1
1回答

弑天下

-在集合的开头或结尾放置一个单曲(字符类)。然后它不会创建字符范围,而是代表文字-字符本身。re.compile('[^-a-zA-Z0-9]')也可以-使用 a转义\, 以指示它是一个文字破折号字符而不是集合内的范围运算符。re.compile(r'[^\-\w]')特殊序列\w等价于集合[a-zA-Z0-9_](“w”代表“单词字符”)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python