MaiaVictor
MaiaVictor

Reputation: 52987

How do I match "abc?def?" but not "abc??def?"

I am trying the following:

.+\?[^\?].+\?

That is, match everything til a "?", then, if no other "?" after that, match everything til another "?". I guess it is not working because the first .+ matches the entire string already.

Upvotes: 0

Views: 1034

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185681

Your description isn't precise, but here's the rules I assume you need your regex to satisfy:

  1. Zero or more characters that are not '?'
  2. A '?'
  3. One or more characters that are not '?'
  4. A '?'

This is actually pretty simple.

[^?]*\?[^?]+\?

Note that this will match a substring of a larger string. If you need to ensure the entire string exactly matches this, throw in ^ and $ anchors:

^[^?]*\?[^?]+\?$

Explanation:

  1. ^

    Start of the string. In a multiline context this also matches start of the line, but you're probably not in a multiline context.

  2. [^?]

    Match anything that's not the literal character '?'.

  3. *

    Match zero or more of the previous token.

  4. \?

    Match a literal '?'.

  5. [^?]

    Match anything that's not the literal character '?'.

  6. +

    Match one or more of the previous token. This ensures that you cannot have two '?' in a row.

  7. \?

    Match a literal '?'.

  8. $

    Match the end of the string (or the end of the line in a multiline context).


Note: I assumed zero or more non-'?' before the first '?'. This will match something like ?abc?. If this is illegal, change the first * to a +.

Upvotes: 4

Related Questions