1

I want to match white space at the beginning of the line but only the the next word is PATCH, PUT, POST or GET

    edit_user_registration GET     /users/edit(.:format)      registrations#edit
                           PATCH   /users(.:format)           registrations#update

In the case above only the second line white space. I tried this:

(^\s*)+(POST|GET|DELETE|PUT|PATCH|OPTIONS)

Problem is this will match even the "PATCH" word but want to match only the whitespace before "PATCH".

code-gijoe
  • 6,327
  • 11
  • 60
  • 99

2 Answers2

2

You can use a lookahead instead:

^\s*(?=(?:POST|GET|DELETE|PUT|PATCH|OPTIONS)\b)

See the regex demo

The last \b makes the pattern match the words only as whole words. If it is not what you need, you can remove it.

A positive lookahead just checks if a pattern matches the text and returns true or false, either fail or pass, without consuming the characters.

Also, (\s*)+ (one or more zero or more whitespace symbols) can be shortened to just \s* (0+ whitespace symbols).

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
0

You can use this :

^\s*(?=POST|GET|DELETE|PUT|PATCH|OPTIONS)

Try it here.

This regex will match the empty string on lines that start by the matched verb. If you don't want this behaviour, change the * to + :

^\s+(?=POST|GET|DELETE|PUT|PATCH|OPTIONS)
Aaron
  • 21,986
  • 2
  • 27
  • 48