如何忽略正则表达式主题字符串中的空格?

时间:2011-01-04 03:00:46

标签: regex whitespace

使用正则表达式模式搜索匹配项时,是否有一种简单的方法可以忽略目标字符串中的空格?例如,如果我的搜索是“猫”,我希望“c ats”或“ca ts”匹配。我不能事先删除空格,因为我需要找到匹配的开始和结束索引(包括任何空格)以突出显示该匹配,并且任何空格都需要用于格式化目的。

6 个答案:

答案 0 :(得分:101)

您可以在正则表达式中的每个其他字符之间粘贴可选的空格字符\s*。虽然被授予,但它会有点冗长。

/cats/ - > /c\s*a\s*t\s*s/

答案 1 :(得分:7)

解决史蒂文对Sam Dufel的回答的评论

  

谢谢,听起来就像是要走的路。但我只是意识到,如果他们按照换行符我只想要可选的空白字符。例如,“c \ n ats”或“ca \ n ts”应匹配。但如果没有新行,就不希望“c ats”匹配。关于如何做到的任何想法?

这应该可以解决问题:

/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/

请参阅this page,查看匹配的“猫”的所有不同变体。

您也可以使用conditionals解决此问题,但正则表达式的javascript风格不支持它们。

答案 2 :(得分:4)

您可以将\s*放在搜索字符串中的每个字符之间,这样如果您正在寻找猫,您可以使用c\s*a\s*t\s*s\s*s

很长,但你当然可以动态地构建字符串。

您可以在此处看到它:http://www.rubular.com/r/zzWwvppSpE

答案 3 :(得分:3)

如果您只想允许空格,那么

\bc *a *t *s\b

应该这样做。要同时允许标签,请使用

\bc[ \t]*a[ \t]*t[ \t]*s\b

如果您还希望在\bcats等字词中找到bobcats,请移除catsup个锚点。

答案 4 :(得分:2)

虽然公认的答案在技术上是正确的,但如果可能的话,一种更实用的方法是将正则表达式和搜索字符串中的空格都去除。

如果您要搜索“我的猫”,而不是:

myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)

只需:

myString.replace(/\s*/g,"").match(/mycats/g)

警告:您不能仅通过用空字符串替换所有空格来在正则表达式上自动执行此操作,因为它们可能出现在否定中,否则会使您的正则表达式无效。

答案 5 :(得分:0)

此方法可用于自动化 (下面的示例解决方案是在python中,虽然显然它可以移植到任何语言):

您可以预先剥离空白并保存非空白字符的位置,以便稍后可以使用它们找出原始字符串中匹配的字符串边界位置,如下所示:

def regex_search_ignore_space(regex, string):
    no_spaces = ''
    char_positions = []

    for pos, char in enumerate(string):
        if re.match(r'\S', char):  # upper \S matches non-whitespace chars
            no_spaces += char
            char_positions.append(pos)

    match = re.search(regex, no_spaces)
    if not match:
        return match

    # match.start() and match.end() are indices of start and end
    # of the found string in the spaceless string
    # (as we have searched in it).
    start = char_positions[match.start()]  # in the original string
    end = char_positions[match.end()]  # in the original string
    matched_string = string[start:end]  # see

    # the match WITH spaces is returned.
    return matched_string

with_spaces = 'a li on and a cat'
print(regex_search_ignore_space('lion', with_spaces))
# prints 'li on'

如果你想更进一步,你可以构造匹配对象并返回它,所以使用这个帮助器会更方便。

此功能的性能当然也可以优化,这个例子只是为了显示解决方案的路径。