Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use them where you need to use/manipulate <em>patterns</em>. For instance, suppose you need to recognise the following pattern:</p> <ul> <li>Any letter, A-Z, either upper or lower case, 5 or 6 times</li> <li>3 digits</li> <li>a single letter a-z (definitely lower case)</li> </ul> <p>(Things like this crop up for zip code, credit card, social security number validation etc.)</p> <p>That's not really <em>hard</em> to write in code - but it becomes harder as the pattern becomes more complicated. With a regular expression, you describe the <em>pattern</em> (rather than the code to validate it) and let the regex engine do the work for you.</p> <p>The pattern here would be something like </p> <pre><code>[A-Za-z]{5,6}[0-9]{3}[a-z] </code></pre> <p>(There are other ways of expressing it too.) Grouping constructs make it easy to match a whole pattern and grab (or replace) different bits of it, too.</p> <p>A few downsides though:</p> <ul> <li>Regexes can become complicated and hard to read quite quickly. Document thoroughly!</li> <li>There are variations in behaviour between different regex engines</li> <li>The complexity can be hard to judge if you're not an expert (which I'm certainly not!); there are "gotchas" which can make the patterns really slow against particular input, and these gotchas aren't obvious at all</li> <li>Some people overuse regular expressions massively (and some underuse them, of course). The worst example I've seen was where someone asked (on a C# group) how to check whether a string was length 3 - this is clearly a job for using String.Length, but someone <em>seriously</em> suggested matching a regex. Madness. (They also got the regex wrong, which kinda proves the point.)</li> <li>Regexes use backslashes to escape various things (e.g. use . to mean "a dot" rather than just "any character". In many languages the backslash itself needs escaping.</li> </ul>
 

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