DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Sub-word Regex Pattern Matching With \B

02.03.2006
| 8174 views |
  • submit to reddit
        The \B regex option can be used to match \w characters ([a-zA-Z_0-9]) inside words.

Some examples for matching a numberstring that contains 332:


string = "12332231 3321705"

string.scan(/\B332\B/) { |x| puts x }

string.scan(/\w+?\B332\B\w+/) { |x| puts x }   # \d for \w is also possible here

a = string.gsub(/(\w+?)\B332\B(\w+)/) { $1 << "9999999" << $2 }   # replaces 332 by 9999999
puts a