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

Usunięta treść Dodana treść
Szymon wro (dyskusja | edycje)
Szymon wro (dyskusja | edycje)
Linia 100:
Wypróbujmy kilka innych tekstów.
 
</pre>
str> abc012dbcd555
pat> \d
abc012dbcd555
~~~ ~~~
[[Wikipedysta:Szymon wro|Szymon Wro]] [[Wikipedysta:Szymon wro|Szymon Wro]]
</pre>
 
Jeśli cię to zaskoczyło, sprawdź w tabeli na górze tej strony: '''\d''' nie ma żadnego związku ze znakiem ''d'', a oznacza pojedynczą cyfrę.
If that surprised you, refer to the table at the top of this page: \d has no relationship to the character d, but rather matches a single digit.
 
A co, jeśli jest więcej niż jeden sposób do poprawnego spasowania wzoru?
What if there is more than one way to correctly match the pattern?
 
<pre>
str> foozboozer
pat> f.*z
foozboozer
~~~~~~~~
22:06, 21 lip 2007 (CEST)[[Wikipedysta:83.21.38.165|83.21.38.165]]
</pre>
 
'''foozbooz''' jest spasowany zamiast tylko '''fooz''', gdyż wyrażenie regularne wybiera najdłuższy możliwy podłańcuch.
foozbooz is matched instead of just fooz, since a regular expression matches the longest possible substring.
 
Oto wzór do wyizolowania pola zawierającego godzinę z separatorem w postaci dwukropka.
Here is a pattern to isolate a colon-delimited time field.
 
<pre>
str> Wed Feb 7 08:58:04 JST 1996
pat> [0-9]+:[0-9]+(:[0-9]+)?
Wed Feb 7 08:58:04 JST 1996
~~~~~~~~
22:06, 21 lip 2007 (CEST)[[Wikipedysta:83.21.38.165|83.21.38.165]]
</pre>
 
"=~" jest operatorem pasowania w odniesieniu do wyrażeń regularnych; zwraca pozycję w łańcuchu, gdzie może być znaleziony pasujący podłańcuch lub ''nil'' jeżeli takowy nie występuje.
"=~" is a matching operator with respect to regular expressions; it returns the position in a string where a match was found, or nil if the pattern did not match.
 
<pre>
ruby> "abcdef" =~ /d/
3
ruby> "aaaaaa" =~ /d/
nil
</pre>
 
{{ProstaNawigacja|spis=Ruby|poprzart=Ruby/Łańcuchy znakowe|poprz=Łańcuchy znakowe|nastart=Ruby/Tablice|nast=Tablice}}