正则表达式:如何替换除 word/sequence 模式以外的所有字符?

Regex: How to replace all characters except a word/sequence of pattern?

我有以下字符串:

"ft-2 MY AWESOME ft-12 APP"
"MY AWESOME APP"
"MY AWESOME APP ft-20"

我想对ft-<NUMBER>部分以外的词做一些修改(在本例中为titleization)。 ft-<NUMBER> 单词可以出现在任何地方。它可以出现多次,也可能根本不存在。字符串操作后,最终结果应如下所示:

"ft-2 My Awesome ft-12 App"
"My Awesome App"
"My Awesome App ft-20"

是否可以在 Ruby 中编写可以进行此转换的任何正则表达式?

我这样试过:

"ft-4 MY AWESOME ft-5 APP".gsub(/(?<=ft-\d\s).*/) { |s| s.titleize }

我得到了这个:ft-4 My Awesome Ft 5 App 在 return。

我不是 100% 确定你想要什么,但我认为你想要小写然后标题化字符串

我的一个项目中有类似的东西

#lib/core_ext/string.rb
class String
  def my_titleize
    humanize.gsub(/\b('?[a-z])/) { .capitalize }
  end
end

humanize(options = {}) public Capitalizes the first word, turns underscores into spaces, and strips a trailing ‘_id’ if present. Like titleize, this is meant for creating pretty output.

The capitalization of the first word can be turned off by setting the optional parameter capitalize to false. By default, this parameter is true.

您的 (?<=ft-\d\s).* 模式匹配任何以 ft-<digits><whitespace> 开头的位置,然后匹配除您 titleize.

的换行符之外的任何 0+ 个字符

您需要匹配不以 ft-<NUMBER> 模式开头的整个单词。那么你所需要的就是将匹配项小写并大写:

s.gsub(/\b(?!ft-\d)\p{L}+/) { | m | m.capitalize }

或者,如果您更喜欢使用 </code> 变量,请添加一个捕获组:</p> <pre><code>s.gsub(/\b(?!ft-\d)(\p{L}+)/) { .capitalize }

Ruby demo

图案详情:

  • \b - 首先,断言字母前的位置(因为下一个消费模式是匹配字母的 \p{L}
  • (?!ft-\d) - 如果接下来的 2 个字母是 ft 后跟一个 - 和一个数字
  • ,则匹配失败的否定前瞻
  • (\p{L}+) - 匹配 1+ 个字母的捕获组(稍后在替换块中用 </code> 引用)</li> </ul> <p><a href="https://ruby-doc.org/core-2.2.0/String.html#method-i-capitalize" rel="nofollow noreferrer"><code>capitalize"returns a copy of str with the first character converted to uppercase and the remainder to lowercase"

R = /
    [[:alpha:]]+ # match one or more uppercase or lowercase letters
    (?=\s|\z)    # match a whitespace or end of string (positive lookahead)
    /x           # free-spacing regex definition mode

def doit(str)
  str.gsub(R) { |s| s.capitalize }
end

doit "ft-2 MY AWESOME ft-12 APP"
  #=> "ft-2 My Awesome ft-12 App" 
doit "MY AWESOME APP"
  #=> "My Awesome App" 
doit "MY AWESOME APP ft-20"
  #=> "My Awesome App ft-20"