Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Backreferences in Regular Expressions

This irb session example shows back referencing, where a token enclosed within round brackets is automatically assigned as a variable. That variable is represented by a dollar ($) symbol followed by it's index number starting at 1.

#match capture = STRONG
irb(main):652:0> "<STRONG>text here</STRONG>"[/<(.*)>.*<\/\1>/]
=> "<STRONG>text here</STRONG>"

irb(main):655:0> "abttba"[/^(.)(.).*\2\1$/]
=> "abttba"
irb(main):658:0> "ab123ttba"[/^(.)(.)(123).*\2\1\3$/]
=> nil
irb(main):659:0> "ab123ttba123"[/^(.)(.)(123).*\2\1\3$/]
=> "ab123ttba123"
irb(main):663:0> "how are you"[/(o)*\1/]
=> nil
irb(main):664:0> "how are you"[/(o).*\1/]
=> "ow are yo"
irb(main):685:0> "how are you"[/(o)[^\1]+\1/]
=> "ow are yo"
irb(main):686:0> "how are you"[/(o)[^\1]+\1u/]
=> "ow are you"
irb(main):692:0> "how is Lucy?"[/(o)[^\1]+\1/]
=> nil
irb(main):693:0> "how is Lucy?"[/(o)[^\1]+\1?/]
=> "ow is Lucy?"

irb(main):702:0> "I eat now?".gsub(/(.)\s(\w+)\s(\w+)(.)/,$1)
=> "I"
irb(main):708:0> "I eat now?".gsub(/(.)\s(\w+)\s(\w+)(.)/,"#{$3} #{$2}")
=> "now eat"
irb(main):711:0> "I eat now?".gsub(/(.)\s(\w+)\s(\w+)(.)/,"#{$3} #{$1} #{$2}#{$4}")
=> "now I eat?"

irb(main):712:0> $1
=> "I"


Backreference support in Ruby uses the following variables:

$` returns everything before the matched string.
$' returns everything after the matched string.
$+ returns whatever the last bracket match matched.
$& returns the entire matched string.

irb(main):713:0> $&
=> "I eat now?"

irb(main):715:0> "I eat now? Mother?".gsub(/(.)\s(\w+)\s(\w+)(.)/,"#{$3} #{$1} #{$2}#{$4}")
=> "now I eat? Mother?"

irb(main):716:0> $'
=> " Mother?"
irb(main):721:0> $'[/M/]
=> "M"

irb(main):732:0> "I'm hungry ... I eat now? Mother?".gsub(/[^.](.)\s(\w+)\s(\w+)(.)/,"#{$3} #{$1} #{$2}#{$4}")
=> "I'm hungry ...now I eat? Mother?"
irb(main):733:0> $`
=> "I'm hungry ..."


Note: These Ruby examples should work from Rubular [rubular.com].
Reference: Unix Regular Expressions: Backreferences [webreference.com]
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS