Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your use of the word "overlapping" is confusing. Apparently, what you meant was that the regex is too greedy, matching everything from the first <code>leftContext</code> to the last <code>rightContext</code>. It seems you figured that out already--and came up with a better approach as well--but there's still at least one potential problem. </p> <p>You said <code>leftContext</code> and <code>rightContext</code> are "plain Strings", by which I assume you meant they aren't supposed to be interpreted as regexes, but they will be. You need to escape them, or any regex metacharacters they contain will cause incorrect results or run-time exceptions. The same goes for your replacement string, although only <code>$</code> and the backslash have special meanings there. Here's an example (notice the non-greedy <code>.*?</code>, too):</p> <pre><code>public static String replaceWithContext(String input, String leftContext, String rightContext, String newString){ String lcRegex = Pattern.quote(leftContext); String rcRegex = Pattern.quote(rightContext); String replace = Matcher.quoteReplacment(newString); Pattern pat = Pattern.compile("(" + lcRegex + ").*?(" + rcRegex + ")", Pattern.DOTALL); </code></pre> <p>One other thing: if you aren't doing any post-match processing on the matched text, you can use <code>replaceAll</code> instead of rolling your own with <code>appendReplacement</code> and <code>appendTail</code>:</p> <pre><code>return input.replaceAll("(?s)(" + lcRegex + ")" + "(?:(?!" + rcRegex + ").)*" + "(" + rcRegex + ")", "$1" + replace + "$2"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload