regex match exclude specific characters in otherwise similar strings

Viewed 915

I have five strings, and I'd like to only match anything that looks like Hello world! without - in it. Example

Hello world!
Hello-world!
Hi world!
Hello~world!
Hello?world!

regex pattern which excludes - is ^((?!-).)*$, but it picks up Hi world.

Desired output

Hello world!
Hello~world!
Hello?world!
2 Answers

You can use a negated character class:

/^Hello\b[^-]\bworld!$/

The word boundaries avoid a match on strings like Helloxworld!

Use

^Hello(?:[^\w-]|_)world!$

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  Hello                    'Hello'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture:
--------------------------------------------------------------------------------
    [^\w-]                   any character except: word characters (a-
                             z, A-Z, 0-9, _), '-'
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    _                        '_'
--------------------------------------------------------------------------------
  )                        end of grouping
--------------------------------------------------------------------------------
  world!                   'world!'
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
Related