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

Sub-word regex pattern matching with \B (See related posts)

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



You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts