How to ignore whitespace in a regular expression subject string?

后端 未结 6 578
梦毁少年i
梦毁少年i 2020-11-27 03:33

Is there a simple way to ignore the white space in a target string when searching for matches using a regular expression pattern? For example, if my search is for \"cats\",

相关标签:
6条回答
  • 2020-11-27 04:06

    Addressing Steven's comment to Sam Dufel's answer

    Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?

    This should do the trick:

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

    See this page for all the different variations of 'cats' that this matches.

    You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.

    0 讨论(0)
  • 2020-11-27 04:06

    While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

    If you want to search for "my cats", instead of:

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

    Just do:

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

    Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

    0 讨论(0)
  • 2020-11-27 04:13

    You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

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

    0 讨论(0)
  • 2020-11-27 04:15

    If you only want to allow spaces, then

    \bc *a *t *s\b
    

    should do it. To also allow tabs, use

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

    Remove the \b anchors if you also want to find cats within words like bobcats or catsup.

    0 讨论(0)
  • 2020-11-27 04:22

    This approach can be used to automate this (the following exemplary solution is in python, although obviously it can be ported to any language):

    you can strip the whitespace beforehand AND save the positions of non-whitespace characters so you can use them later to find out the matched string boundary positions in the original string like the following:

    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'
    

    If you want to go further you can construct the match object and return it instead, so the use of this helper will be more handy.

    And the performance of this function can of course also be optimized, this example is just to show the path to a solution.

    0 讨论(0)
  • 2020-11-27 04:23

    You could put \s* inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s

    It's long but you could build the string dynamically of course.

    You can see it working here: http://www.rubular.com/r/zzWwvppSpE

    0 讨论(0)
提交回复
热议问题