0

How can I transform a string into a regex string, properly escaping all regex-specific characters? I am using interpolation to build the regex string to allow users to customize the regex without having to touch the code (or expecting them to know regex)

Example

custom_text = "Hello"    
my_regex = /#{custom_text}:\s*(\d+)/i

Which results in the following regex when my code uses it

/Hello:\s*(\d+)/i

This allows users to perhaps provide language localizations without having to worry about figuring out where my regex is used, how it's used, or whether they will break the script if they changed something.

However if they wanted to include things like periods or question marks like Hello?, I would probably need to escape them first.

1 Answer 1

5

Use Regexp.escape:

my_regex = /#{Regexp.escape(custom_text)}:\s*(\d+)/i

For example:

>> puts /#{Regexp.escape('Hello?')}/.inspect
/Hello\?/
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, that's a convenient method :)
@Keikoku: As is Regexp.union.
It's also aliased to Regexp.quote, just for completeness' sake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.