15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

170<br />

Finding Strings with Regular Expressions<br />

This finds buz and buzzzz but not bu because the (+) wildcard needs to find<br />

at least a z character.<br />

Pattern matching with ranges<br />

Wildcards can match zero or more characters, but sometimes you may want<br />

to know whether a particular character falls within a range or characters. To<br />

do this, you can use ranges. For example, if you want to know whether a<br />

character is any letter, you could use the pattern [a-z] as follows:<br />

bu[a-z]<br />

This finds strings, such as but, bug, or bus, but not bu (not a three-character<br />

string). Of course, you don’t need to search <strong>for</strong> letters from a to z. You can<br />

just as well search <strong>for</strong> the following:<br />

bu[d-s]<br />

This regular expression finds bud and bus but not but (because the t lies outside<br />

the range of letters from d to s).<br />

You can also use ranges to check whether a character falls within a numeric<br />

range, such as<br />

21[0-9]<br />

This finds the strings 212 and 210. If you only wanted to find strings with<br />

numbers between 4 and 7, you’d use this regular expression:<br />

21[4-7]<br />

This finds the strings 215 but not the strings 210 or 218 because both 0 and 8<br />

lie outside the defined range of 4–7. Table 3-6 shows examples of different<br />

regular expressions and the strings that they find.<br />

This section shows a handful of regular expression symbols you can use to<br />

search <strong>for</strong> string patterns. A lot more regular expressions can per<strong>for</strong>m all<br />

sorts of weird and wonderful pattern searching, so you can always find out<br />

more about these other options by browsing www.regular-expressions.<br />

info.<br />

By stringing multiple regular expression wildcards together, you can search<br />

<strong>for</strong> a variety of different string patterns, as shown in Table 3-6.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!