I'm trying to covert a forum where BBCode tag are upcase. I need to write a parser to downcase my tag, from [QUOTE] to [quote], from [/QUOTE] to [/quote], etc etc.
I write this:
string.gsub(/#\[(.*?)\]/, ' \1'.downcase)
but of course it doesn't work!
How can I fix it?
#
is wrong. ()
). You can refer to the entire match. [
, ]
, /
will remain as is by downcase
, so no harm including them. In fact, your regex already possibly includes /
in the capture, so it does not make sense to exclude just [
and ]
from the capture. '\\1'.downcase
did not work because that is equivalent to '\\1'
. To perform a method on the match, you need a block. .*?
in the regex intends to capture nested brackets correctly, but that works only half way. If you had "[foo [bar] baz]"
, then by \\[(.*?)\\]
, you can avoid matching "[foo [bar] baz]"
and "[bar] baz]"
, but it still mathces "[foo [bar]"
. So .*?
is not meaningful. Considering the points above, you can do the following if you need to consider nested brackets:
string.gsub(/\[[^\[\]]+\]/, &:downcase)
Otherwise,
string.gsub(/\[.+\]/, &:downcase)
You can modify the match by using the block version of gsub
.
s.gsub(/\[(.+?)\]/) { |match| match.downcase }
or the more compact version
s.gsub(/\[(.+?)\]/, &:downcase)
Also note there was a #
that was preventing the regexp to match.
Example:
s = "from [QUOTE] to [quote], from [/QUOTE] to [/quote]"
s.gsub(/\[(.*?)\]/, &:downcase)
=> "from [quote] to [quote], from [/quote] to [/quote]"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.