Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(This is a continuation of the conversation from the comments to Evan's answer.) </p> <p>Here's what happens when your (corrected) regex is applied: First, the <code>.+</code> matches the whole string. Then it backtracks, giving up most of the characters it just matched until it gets to the point where the <code>B=</code> can match. Then the <code>(.+?)</code> matches (and captures) everything it sees until the next part, the semicolon, can match. Then the final <code>.+</code> gobbles up the remaining characters.</p> <p>All you're really interested in is the "B=" and the ";" and whatever's between them, so why match the rest of the string? The only reason you have to do that is so you can replace the whole string with the contents of the capturing group. But why bother doing that if you can access contents of the group directly? Here's a demonstration (in Java, because I can't tell what language you're using):</p> <pre><code>String s = "A=abc;B=def_3%^123+-;C=123;"; Pattern p = Pattern.compile("B=(.*?);"); Matcher m = p.matcher(s); if (m.find()) { System.out.println(m.group(1)); } </code></pre> <p>Why do a 'replace' when a 'find' is so much more straightforward? Probably because your API makes it easier; that's why we do it in Java. Java has several regex-oriented convenience methods in its String class: <code>replaceAll()</code>, <code>replaceFirst()</code>, <code>split()</code>, and <code>matches()</code> (which returns <code>true</code> iff the regex matches the <em>whole</em> string), but not <code>find()</code>. And there's no convenience method for accessing capturing groups, either. We can't match the elegance of Perl one-liners like this:</p> <pre><code>print $1 if 'A=abc;B=def_3%^123+-;C=123;' =~ /B=(.*?);/; </code></pre> <p>...so we content ourselves with hacks like this:</p> <pre><code>System.out.println("A=abc;B=def_3%^123+-;C=123;" .replaceFirst(".+B=(.*?);.+", "$1")); </code></pre> <p>Just to be clear, I'm not saying not to use these hacks, or that there's anything wrong with Evan's answer--there isn't. I just think we should understand <em>why</em> we use them, and what trade-offs we're making when we do.</p>
 

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