yevg
yevg

Reputation: 1966

Regex - match a pattern containing two dashes but not three

I trying to find the correct regex to match the following pattern:

any_characters--any_characters

but not this one:

any_characters---any_characters

The difference being that the undesired pattern has exactly three subsequent dashes and the desired pattern has exactly two.

Ive tried (.*)--(.*) but of course this doesnt work because a dash is matched by the .* so the above regex will match anything as long as it has two or more dashes.

Upvotes: 0

Views: 1098

Answers (2)

The fourth bird
The fourth bird

Reputation: 163332

If lookarounds are supported and you want to match words without spaces and the word can not contain --- but must contain -- is

(?<!\S)(?!\S*---)\S+--\S+
  • (?<!\S) Assert what is on the left is not a non whitespace char
  • (?!\S*---) Assert what is on the right is not 3 times ---
  • \S+--\S+ Match 1+ non whitespace chars, -- and again 1+ non whitespace chars

Regex demo

Upvotes: 4

Xenobiologist
Xenobiologist

Reputation: 2151

Like already written in a comment, this should do the trick.

 '.*[^-]--[^-].*'

Upvotes: 2

Related Questions