The Nomad The Nomad -5 years ago 115
Ruby Question

How to check for [ ] at beginning and end of string

How do I check for

at the beginning and
at the end of a string using a regular expression?

I am 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