regex find spaces in double quotes

Regex Find Spaces in Double Quotes

When working with large amounts of data, it can be helpful to use regular expressions to find specific patterns. One common task is to find spaces within double quotes. Here are a few ways to accomplish this:

Method 1: Using Lookarounds

One way to find spaces within double quotes is by using a positive lookbehind and lookahead:


(?<=\")[^\"]*\s[^\"]*(?=\")

This regex pattern searches for any space character (represented by the \s character class), located between two sets of non-double-quote characters (represented by [^\"]*). The positive lookbehind (?<=\") and lookahead (?=\") ensure that the pattern is only matched if it appears within double quotes.

Method 2: Using Capture Groups

Another way to find spaces within double quotes is by using capture groups:


\"([^\"]*\s[^\"]*)\"

This regex pattern captures any sequence of non-double-quote characters, followed by a space, followed by another sequence of non-double-quote characters, as long as the entire sequence is enclosed in double quotes.

Method 3: Using Alternation

A third method for finding spaces within double quotes is by using alternation:


\"[^\"\s]*\s[^\"\s]*\"

This regex pattern matches any sequence of non-double-quote, non-space characters, followed by a space, followed by another sequence of non-double-quote, non-space characters, as long as the entire sequence is enclosed in double quotes.

No matter which method you choose, regular expressions can be a powerful tool for finding and manipulating text data.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe