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.
Pewne znaki i kombinacje znaków które mają specjalne znaczenie w tych wzorcach:
<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▼
\d digit character; same as [0-9]▼
</tr><tr>
\D non-digit character▼
\b backspace (0x08) (only if in a range specification)▼
</tr><tr>
\b word boundary (if not in a range specification)▼
\B non-word boundary▼
</tr><tr>
* zero or more repetitions of the preceding▼
+ one or more repetitions of the preceding▼
</tr><tr>
{m,n} at least m and at most n repetitions of the preceding▼
? at most one repetition of the preceding; same as {0,1}▼
</tr><tr>
| either preceding or next expression may match▼
</tr><tr>
</tr><tr>
</tr><tr>
</tr><tr>
</tr><tr>
</tr><tr>
</tr><tr>
</tr><tr>
</tr><tr>
</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.
|