Over a million developers have joined DZone.

Sub-word Regex Pattern Matching With \B

DZone's Guide to

Sub-word Regex Pattern Matching With \B

Free Resource
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


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}