0

I have a String such as

somet3x70rnumb3r5.3.1*@:ch4r5*

I need to wrap everything that isn't *, star character, with a Pattern Quote \Q...\E and replace the * with .*. It should give this:

\Qsomet3x70rnumb3r5.3.1\E.*\Q@:ch4r5\E.*

I can do this with string traversal, splitting on * (or any character I specify), and building a string step by step, but I'd like to do use regexes and Pattern class utilities if possible.

Another example with specified character ? which would be replaced by .:

123?4?

should give

\Q123\E.\Q4\E.

I was thinking of using groups, but I need groups around every zone because each has to be either wrapped or replaced by another character.

My goal is to create a Pattern String from a given String but only consider the areas matching the specified character and ignoring the rest (even if it contains regex patterns).

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • soyou basically wanna escape the matched string with a backslash ?? like ... `\somet3x70rnumb3r5.3.1.*\@:ch4r5\.*` and `\123.\4.` ?? ` – PermGenError Jan 14 '13 at 22:29
  • No. I want the string areas around some specified character to be wrapped like `\Q\E` and the specified character to be replaced by some other. `\Q---\E` is used by Pattern to ignore anything inside it. – Sotirios Delimanolis Jan 14 '13 at 22:31
  • but AFAIK `\Qanythinghere\E` <==> `\anythinghere` in regex world .. check here http://docs.oracle.com/javase/tutorial/essential/regex/literals.html – PermGenError Jan 14 '13 at 22:32
  • I dunno about that, I think it needs the end tag, but I want only the `anythinghere` to be ignored by Pattern, while everything outside to be considered. – Sotirios Delimanolis Jan 14 '13 at 22:32
  • The example I gave above contains period `.`. This character would be considered as any character in a Pattern matcher, unless it was within `\Q\E`, then it would be considered as a literal. – Sotirios Delimanolis Jan 14 '13 at 22:35

2 Answers2

1

It'll be simpler if you don't worry about building a one-liner. A one-liner is probably possible, but it will be a pain. Instead, I suggest you do something like this:

str = str.replaceAll("(?<!^)\\*(?!$)", "\\E.*\\Q")
         .replaceAll("(?<!^)\\?(?!$)", "\\E.\\Q");
str = "\\Q" + str + "\\E";

Simpler to write, and much easier to understand.

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
  • 1
    @SotiriosDelimanolis - Sure, that's a *zero-width lookbehind assertion.* Check out [this regular-expressions.info page](http://www.regular-expressions.info/lookaround.html) and [this Stack Overflow question](http://stackoverflow.com/q/2973436/399649) for a much better explanation than I'll be able to come up with. – Justin Morgan - On strike Jan 15 '13 at 15:30
1

Something like this?

String s = "abc*efg?123";
s = s.replaceAll("([^\\*\\?]+)", "\\\\Q$1\\\\E");
s = s.replaceAll("\\*", ".*");
s = s.replaceAll("\\?", ".");

Results in \Qabc\E.*\Qefg\E.\Q123\E

JohnnyK
  • 1,103
  • 6
  • 10