user336635
user336635

Reputation: 2281

Invalid regex in Qt yet in regex coach this same regex is valid

I've got following regex which seems to be a valid regex according to regex coach but qt's regexp.isValid says something else. Could anyone tell me what's the story with this expression:

^[^,\.:;\*<>\[\]\+\"\\\/]+\.cpp$

Upvotes: 0

Views: 171

Answers (2)

MSalters
MSalters

Reputation: 179779

/ should not be single-escaped. It's a regular character in C++. [ nor * need regex escaping inside a class. . needs regex escaping, not C++ escaping.

Rules:

  • If C++ requires escaping (e.g. "), use a single \
  • If regex requires escaping (e.g. ]), use a double \
  • If regex and C++ both requires escaping, use a triple \
  • When you need a single \ for your regex syntax, C++ requires escaping so you get \\
  • When escaping \ itself, you need three \ in addition to \ itself, so you get 4 .

So:

"^[^,\.:;*<>[\\]\+\"\\/]+\\.cpp$"

Upvotes: 1

stema
stema

Reputation: 92976

According to http://doc.qt.nokia.com/latest/qregexp.html Qt/C++ needs double escaping, so try to double each backslash like this:

^[^,.:;*<>[\\]+"\\\\/]+\\.cpp$

I removed also some of them, because inside a character class they don't need to be escaped.

Upvotes: 0

Related Questions