Generate Ruby code from a regex
Drop a pattern in, pick flags, and get a Ruby snippet — match, scan, gsub, split — with both the /.../ literal and Regexp.new constructor forms.
input = "Reach alice@example.com or bob@test.org."
re = /\\b\\w+@\\w+\\.\\w+\\b/
re_alt = Regexp.new("\\\\b\\\\w+@\\\\w+\\\\.\\\\w+\\\\b")
is_match = !!(input =~ re)
first = input.match(re)
all = input.scan(re)
replaced = input.gsub(re, "[email]")
parts = input.split(re)
puts({
is_match: is_match,
first: first && first[0],
all: all,
replaced: replaced,
parts: parts,
}.inspect)How to use a regex in Ruby
Ruby uses the Onigmo engine and exposes regex as a first-class literal: /pattern/imx. The =~ operator returns the match index or nil.
- 01
Type a pattern
Slashes inside the pattern are auto-escaped. The output includes both the /…/ literal and a Regexp.new(...) constructor form for dynamic patterns.
Patterns are parsed with the JavaScript RegExp constructor, so syntax errors surface immediately and engine quirks like Unicode property escapes (\p{L}) require the u flag.
patternECMAScriptliteralregexinput · literalpattern · regex/\b\w+@\w+\b/
loaded · ECMAScripttarget · ready - 02
Tune flags
JS i/m/x map to /pat/i, /pat/m, /pat/x. Note that Ruby's m flag is JS's s — it makes . match newlines. Ruby has no equivalent to JS m.
Each flag character mirrors the ECMAScript literal: g enables iteration, i folds case, m anchors per line, s lets . match newlines, u unlocks proper Unicode, y is sticky, and d emits indices.
flagssampleg · i · mliveconfig · optionsflags · flags/pat/im
flags applied · livelive · preview - 03
Read the snippet
Includes =~ (boolean-ish), match (first), scan (all), gsub (replace), and split — printed as an inspectable hash.
The generator rewrites the regex for the target language — handling string-literal escaping, raw-string prefixes, and engine-specific syntax tweaks.
codegentargetsnippetcopyrun · outputpreview · codeinput.scan(re)
snippet · livecode · ready - 04
Copy code
One click copies the full snippet — paste into a .rb file, an irb session, or a Rails console.
Copy writes via navigator.clipboard.writeText, so nothing transits the network and the output is byte-identical to what you see on screen.
copyexportclipboardblobexport · exportedready · savedCopied
ready to shipsuccess
Regex patterns that don't melt down
Use named groups
(?<year>\d{4}) reads better than $1 and survives reordering. Supported in ECMAScript 2018+.
Anchor strictly
Use ^/$ with the m flag when matching whole lines. Without anchors, partial matches sneak through.
Avoid catastrophic backtracking
Nested quantifiers like (a+)+ can explode. Run patterns through ReDoS Detector first.
Escape every literal
Backslash any meta character you want literally: \.\$\^\*\+\?\(\)\[\]\{\}\|\\.
Test edge cases
Empty string, single character, unicode, the maximum length you expect — write fixtures for each.
Patterns aren’t parsers
Don’t parse HTML, JSON, or balanced parens with regex. Use a proper parser when the grammar is recursive.
When to generate Ruby regex code
Skip the boilerplate when wiring a pattern into a Rails app, a Jekyll plugin, or a sysadmin script.
Rails validation
Drop a regex into a model with validates :field, format: { with: re }. Compiles through the JavaScript RegExp constructor — engine quirks (Unicode property escapes, sticky matching, named groups) work when their flags are on. Error messages cite the exact position of any syntax issue.
ReDoS-safeERB / Liquid filtering
Use gsub in template helpers to sanitise output. Pairs with the ReDoS detector to catch catastrophic backtracking before you deploy. A pattern that handles 1k-character input fine can become a denial-of-service vector on attacker-controlled 1M-character input.
ECMA-compliantMigrations
Run scan/gsub during a rake task to clean up legacy data. Output exports as JavaScript, Python re, Java util.regex, .NET System.Text.RegularExpressions, PCRE, and POSIX — language quirks are highlighted on conversion so you don't ship a JS-only pattern to a Go service.
spec-gradeSysadmin scripts
Pipe log files into Ruby one-liners that match and aggregate. Capture groups (named or numbered) round-trip cleanly into replacement strings, JSON output, or CSV extraction without re-typing. Backreferences ($1, ${name}) preserve semantics across languages.
cross-engineAPI normalisation
Pre-validate input shape in a Sinatra/Rack middleware. Test against edge cases — empty input, single character, max length, multibyte boundaries — to catch off-by-one and zero-length match bugs before they reach production.
test-readyCap deploy hooks
Parse Capistrano output with regex in deploy callbacks. All matching runs client-side so secret patterns never leave the browser. Useful when the pattern itself is sensitive (PII regexes, internal data formats, security filters).
production-readyFrequently asked questions
Something missing?
Tell us what you need. We ship the top requests every two weeks.