Ruby/Wyrażenia regularne: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Nie podano opisu zmian
Linia 1:
== Wyrażenia regularne ==
 
Stwórzmy bardziej interesujący program. Tym razem sprawdzimy czy łańcuch pasuje do opisu zakodowanego jako ścisły wzorzec.
Let's put together a more interesting program. This time we test whether a string fits a description, encoded into a concise pattern.
 
Pewne znaki i kombinacje znaków które mają specjalne znaczenie w tych wzorcach:
There are some characters and character combinations that have special meaning in these patterns, including:
 
<table class="wikitable">
[] range specificication (e.g., [a-z] means a letter in the range a to z)
<tr>
\w letter or digit; same as [0-9A-Za-z]
<th>Symbol</th>
\W neither letter or digit
<th>Opis</th>
\s space character; same as [ \t\n\r\f]
</tr><tr>
\S non-space character
<td>[]</td><td> range specificication (e.g., [a-z] means a letter in the range a to z)</td>
\d digit character; same as [0-9]
</tr><tr>
\D non-digit character
<td>\w </td><td>letter or digit; same as [0-9A-Za-z]</td>
\b backspace (0x08) (only if in a range specification)
</tr><tr>
\b word boundary (if not in a range specification)
<td>\W </td><td>neither letter or digit</td>
\B non-word boundary
</tr><tr>
* zero or more repetitions of the preceding
<td>\s </td><td>space character; same as [ \t\n\r\f]</td>
+ one or more repetitions of the preceding
</tr><tr>
{m,n} at least m and at most n repetitions of the preceding
<td>\S </td><td>non-space character</td>
? at most one repetition of the preceding; same as {0,1}
</tr><tr>
| either preceding or next expression may match
<td>\d </td><td>digit character; same as [0-9]</td>
() grouping
</tr><tr>
<td>\D </td><td>non-digit character</td>
</tr><tr>
<td>\b </td><td>backspace (0x08) (only if in a range specification)</td>
</tr><tr>
<td>\b </td><td>word boundary (if not in a range specification)</td>
</tr><tr>
<td>\B </td><td>non-word boundary</td>
</tr><tr>
<td>* </td><td>zero or more repetitions of the preceding</td>
</tr><tr>
<td>+ </td><td>one or more repetitions of the preceding</td>
</tr><tr>
<td>{m,n} </td><td>at least m and at most n repetitions of the preceding</td>
</tr><tr>
<td>? </td><td>at most one repetition of the preceding; same as {0,1}</td>
</tr><tr>
<td>| </td><td>either preceding or next expression may match</td>
</tr><tr>
<td>()</td><td>grouping</td>
</tr>
</table>
 
The common term for patterns that use this strange vocabulary is regular expressions. In ruby, as in Perl, they are generally surrounded by forward slashes rather than double quotes. If you have never worked with regular expressions before, they probably look anything but regular, but you would be wise to spend some time getting familiar with them. They have an efficient expressive power that will save you headaches (and many lines of code) whenever you need to do pattern matching, searching, or other manipulations on text strings.