Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Generally, a regular expression engine will find the leftmost, longest match in a string (unless you explicitly tell it not to).</p> <p>So the regex <code>X+</code> will always match <code>XXXXX</code> in <code>testXXXXX.</code>.</p> <p>However, if there is more than one potential match in the string, the standard <code>find</code> methods will always find the first, not necessarily the longest match (say, in <code>test1XXtest2XXXXX.</code>). To find the longest match here, you need to use the <code>findall</code> method of your regex engine and then measure the length of all the matches.</p> <p>In C#, this might look like this:</p> <pre><code>StringCollection resultList = new StringCollection(); Regex regexObj = new Regex("[ ]+"); Match matchResult = regexObj.Match(subjectString); while (matchResult.Success) { resultList.Add(matchResult.Value); matchResult = matchResult.NextMatch(); } </code></pre> <p>(and after that, find the longest string in <code>resultList</code>.)</p> <p>There is a problem, though, if potential matches can overlap. Take for example the regex</p> <pre><code>AB+A </code></pre> <p>and the string</p> <pre><code>ABABBA </code></pre> <p>If you apply the regex, you will only find <code>ABA</code> because the regex engine has consumed the second <code>A</code> after the first match, so it starts the second attempt at the <code>B</code> of <code>BBA</code> and fails, of course. This is a consequence of the "leftmost-longest" behaviour, and if you want to circumvent that, you'd have to reapply the regex "manually" to the entire string, then to the entire string minus the first character, then to the entire string minus the first two characters, etc.</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