Search code examples
javaregexwords

Regex for "* word"


Any Regex masters out there? I need a regular expression in Java that matches:

"RANDOMSTUFF SPECIFICWORD"

Including the quotation marks. Thus I need

to match the first quote,
RANDOMSTUFF (any number of words with spaces between preceding SPECIFICWORD)
SPECIFICWORD (a specific word which I won't specify here.)
and the ending quote.

I don't want to match things such as:

RANDOMSTUFF SPECIFICWORD
"RANDOMSTUFF NOTTHESPECIFICWORD"
"RANDOMSTUFF SPECIFICWORD MORERANDOMSTUFF"

Solution

  • \".*\sSPECIFICWORD\"

    If you don't want to allow quotes in between, use \"[^"]*\sSPECIFICWORD\"

    . matches any character
    * says 0 or more of the preceding character (in this case, 0 or more of any characters)
    \s matches any whitespace character
    SPECIFICWORD will be treated as a string literal, assuming there are no special characters (escape them if there are)
    \" matches the quote
    [^"] means any character except a quote (the ^ is what makes it 'except')

    Also, this link could be useful. Regex's are powerful expressions and are applicable across virtually any language, so it would be a good thing to become comfortable with using them.

    EDIT:

    As several other posters have pointed out, adding ^ to the beginning and $ to the end will only match if the entire line matches.

    ^ matches the beginning of the line
    $ matches the end of the line