尝试使用gsub
来转换字符串的前进顺序同意字符以及字符'qu'
的组合。如何通过正则表达式((two specific character in a specific order) OR (any character in a set of characters)) any number of times
我尝试过以下无效:
"stupid".gsub( /([(qu)]*[^aeiou]*)(.*)/, '\2\1') + 'ay' #=> "upidstay" correct!
"uce".gsub( /([(qu)]*[^aeiou]*)(.*)/, '\2\1') + 'ay' #=> "eucay" NOT correct :(
"stupid".gsub( /((qu)*[^aeiou]*)(.*)/, '\2\1') + 'ay' #=> "stay"
"uce".gsub( /([(qu)|[^aeiou]]*)(.*)/, '\2\1') + 'ay' #=> "eucay" # why does just a "u" match?
我认为它归结为我不知道如何在[]
中选择多个特定的连续字符,我认为它是[(qu)]
,但为什么只有u
得到匹配?
答案 0 :(得分:1)
这是你在找什么?
cons = "(?:qu|[^aeiou])"
"uce".gsub(/^(#{cons}+)(.*)/,'\2\1') + 'ay' # => uceay
"stupid".gsub(/^(#{cons}+)(.*)/,'\2\1') + 'ay' # => upidstay
"quduck".gsub(/^(#{cons}+)(.*)/,'\2\1') + 'ay' # => uckquday
答案 1 :(得分:1)
字符类[]
指定要匹配的字符,以便[(qu)]
匹配(
,q
,u
和)
Piglatin RegEx:/((?:(?:qu))*[^aeiou]*)(\w*)/
替换为:'\2\1'
并附加'ay'
代码:
"quick".gsub( /((?:(?:qu))*[^aeiou]*)(\w*)/, '\2\1') + 'ay'
参见示例here。