I have a form, that sends the contents of a text field to my Rails application and I have to generate a regular expression of this string.
I tried it like this:
regex = /#{params[:text]}/
In general this is working, but if brackets or special characters are contained in the string, this method will not work.
I don't want Rails to take care of the chars. They should be escaped automatically.
I tried it like this:
/\Q#{params[:text]}\E/
but this isn't working either.
You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/. To know more about regex ,watch this videos. You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.
The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
You should use Regexp.escape
regex = /#{Regexp.escape(params[:text])}/ # in rails models/controllers with mongoid use: # ::Regexp.escape(params[:text]) instead. ([more info][2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With