0

I am struggling with a regular expression. It is supposed to match only those strings that are a list of 3 words separated by |.

A word may contain any character (no newline etc., of course) but |

Examples:

word01|wörd|wä4rd # only this should be matched
word04|würd|wä4rd|of
word02|wörd|wä4rd|off|j
word01|wörd

I'd like to match those that have exactly 2 |. A simple count function could do it, but that is not available in my case. So I need a regular expression.

This obviously does not do the trick:

^[^\|]+\|[^\|]+\|+[^\|]$

What's the correct regular expression? What's wrong with my approach?

3 Answers 3

2

You have misplaced the last + sign, instead of:

^[^\|]+\|[^\|]+\|+[^\|]$

use

^[^\|]+\|[^\|]+\|[^\|]+$
//               ^____^
Sign up to request clarification or add additional context in comments.

4 Comments

[^\|] matches any character except pipe and backslash, there is no escaping needed for the pipe in that case.
@sphere: I agree that | doesn't need to be escaped, but [\|] doesn't match \ or |, it should be [\\|] to match \ .
I agree. Interesting that it seems to have no difference if [^\|] or [^|] is used.
Yes, I misplaced that. What a foolish mistake.
2

Correct would be: '^[^|]+\|[^|]+\|[^|]+$'

Comments

1

You can simply do this

^([^|]+\|){2}[^|]+$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.