简体   繁体   English

带Ruby的小写BBCode标签

[英]Downcase BBCode Tag with Ruby

I'm trying to covert a forum where BBCode tag are upcase. 我正在尝试掩盖BBCode标签大写的论坛。 I need to write a parser to downcase my tag, from [QUOTE] to [quote], from [/QUOTE] to [/quote], etc etc. 我需要编写一个解析器来将我的标签从[QUOTE]转换为[quote],从[/ QUOTE]转换为[/ quote],等等。

I write this: 我这样写:

string.gsub(/#\[(.*?)\]/, ' \1'.downcase)

but of course it doesn't work! 但是当然不行!

How can I fix it? 我该如何解决?

  • Your # is wrong. 您的#错误。
  • You don't need to use capture (by putting () ). 您不需要使用捕获(通过放入() )。 You can refer to the entire match. 您可以参考整个比赛。 [ , ] , / will remain as is by downcase , so no harm including them. []/将保留为downcase ,因此包括它们在内不会造成任何伤害。 In fact, your regex already possibly includes / in the capture, so it does not make sense to exclude just [ and ] from the capture. 实际上,您的正则表达式可能已经在捕获中包含了/ ,因此从捕获中仅排除[]是没有意义的。
  • Your '\\1'.downcase did not work because that is equivalent to '\\1' . 您的'\\1'.downcase无效,因为它等效于'\\1' To perform a method on the match, you need a block. 要在比赛中执行方法,您需要一个块。
  • I assume your .*? 我假设您是.*? 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]" . 如果您有"[foo [bar] baz]" ,则通过\\[(.*?)\\]可以避免匹配"[foo [bar] baz]""[bar] baz]" ,但仍然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 . 您可以使用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]" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM