-1

尝试使用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匹配?

4

2 回答 2

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 
于 2013-03-09T03:44:38.540 回答
1

字符类[]指定要匹配的字符,因此将[(qu)]匹配(、和qu)

皮拉丁正则表达式:/((?:(?:qu))*[^aeiou]*)(\w*)/

替换为:'\2\1'并附加一个'ay'

代码:

"quick".gsub( /((?:(?:qu))*[^aeiou]*)(\w*)/, '\2\1') + 'ay'

请参见此处的示例。

于 2013-03-09T03:44:48.807 回答