The Nomad The Nomad - 1 year ago 82
Ruby Question

Ruby Regex - want to check for brackets [ ] at beginning and end

How do I check for

at the beginning and
at the end of a string in
using Regex?

I am basically trying to check if the string can be used by

is what I came up with, but doesn't seem like it's working.

Answer Source

There is no need for a regex, use start_with and end_with:

s = "[text\nhere]"
puts s.start_with?("[") and s.end_with?("]")
# => true

See Ruby demo

If you need a regex, you may use


to check if any string starts with [ and ends with ].


  • \A - start of a string
  • \[ - a literal [
  • .* - 0+ any characters, even incl. a newline due to the /m modifier)
  • \] - a closing ]
  • \z - the very end of the string.

See the regex demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download