The Nomad The Nomad - 5 months ago 16
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
Ruby
using Regex?

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

/\A[\w\z]/
is what I came up with, but doesn't seem like it's working.

Answer

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

/\A\[.*\]\z/m

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

Explanation:

  • \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