3

Let's say I've got a regex expression utilizing some of the special chars, but also a portion with 'normal' text that just happens to have some symbols in. Let's also say I'm too lazy to start escaping every "would-be" special character in the 'normal text' part.

How can I enclose the 'normal' text bit so that Regex doesn't start throwing a fit when it thinks it's come across a special character (when really it hasn't) ?

As an example, let's say I search for the text:

.*Hello it's true that ([6*.5]^2=9).

I certainly don't want to laboriously use the escape char each time any of the special chars appears in that maths section (or the apostrophe in "don't"). On the other hand, I DO want to treat the .* bit at the start as special characters.

So can I enclose the Hello it's true that ([6*.5]^2=9) section so that Regex treats it as normal text and not special?

I'm using Notepad++ to do a find and replace, but hopefully, any answer will be the same no matter what the program.

1

Some tools allow you to change whether special characters must be escaped by default. For instance, vi (and clones) has a magic mode which controls this. That can let you reduce the amount of escaping needed.

| improve this answer | |
  • Wow, so there's nothing in the default spec? Just this one thing alone makes me hate Regex more than anything else that might otherwise be wrong with it. – Dan W May 23 '15 at 21:35
  • Someone might recall a different case. The vi "magic" feature by the way is reflected in the differences between BREs and EREs (grep vs egrep), etc. – Thomas Dickey May 23 '15 at 21:40
  • I found out that it is possible with most flavours of Regex after all. Bitterness starting to fade... :) See my own answer to this Q. – Dan W May 25 '15 at 12:38
  • Not exactly: it is the Perl-derived flavor which pcre provides, and recent versions of Notepad++ use. POSIX regex's don't do that (though there may be some aspect which I'm overlooking). Perl is not POSIX, of course. – Thomas Dickey May 25 '15 at 20:23
1

Try \Q to start a literal, and end with \E.

This works with many flavours of Regex, though Java may have problems for instance.

Information obtained from: http://www.regular-expressions.info/characters.html

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.