Alexey Orlov
Alexey Orlov

Reputation: 2804

Regex: match one or more characters, interspersed with spaces

Is there a way to build a regular expression, which matches substrings like these (- means one and the same character, hyphen, for instance):

'-'
' -'
'- --'
' --- '
'- -- ---  '

but never simple '\s+'?

Upvotes: 1

Views: 173

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

To match sequences of whitespaces and hyphens with at least 1 hyphen, you may use

\s*(?:-\s*)+

See the regex demo.

Details

  • \s* - 0+ whitespaces
  • (?:-\s*)+ - 1 or more repetitions of
    • - - a hyphen
    • \s* - 0+ whitespaces.

Upvotes: 1

Related Questions