Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For your first question, make it lazy. You can put a question mark after the quantifier and then the quantifier will match as less as possible.</p> <pre><code>(?&lt;=an).*?(?=for) </code></pre> <p>I have no idea what the additional <code>.</code> at the end is good for in <code>.*.</code> its unnecessary.</p> <p>For your second question you have to define what a "word" is. I would say here probably just a sequence of non whitespace followed by a whitespace. Something like this</p> <pre><code>\S+\s </code></pre> <p>and repeat this 3 times like this</p> <pre><code>(?&lt;=an)\s(\S+\s){3}(?=for) </code></pre> <p>To ensure that the pattern mathces on whole words use word boundaries</p> <pre><code>(?&lt;=\ban\b)\s(\S+\s){1,5}(?=\bfor\b) </code></pre> <p>See it <a href="http://regexr.com?2uf3m" rel="nofollow">online here on Regexr</a></p> <p><code>{3}</code> will match exactly 3 for a minimum of 1 and a max of 3 do this <code>{1,3}</code></p> <p><strong>Alternative:</strong></p> <p>As dma_k correctly stated in your case here its not necessary to use look behind and look ahead. See <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Matcher.html#group%28int%29" rel="nofollow">here the Matcher documentation about groups</a></p> <p>You can use capturing groups instead. Just put the part you want to extract in brackets and it will be put into a capturing group.</p> <pre><code>\ban\b(.*?)\bfor\b </code></pre> <p>See it <a href="http://regexr.com?2uf3j" rel="nofollow">online here on Regexr</a></p> <p>You can than access this group like this</p> <pre><code>System.out.println("I found the text: " + matcher.group(1).toString()); ^ </code></pre> <p>You have only one pair of brackets, so its simple, just put a <code>1</code> into <code>matcher.group(1)</code> to access the first capturing group.</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