正则表达式匹配对特定字符的出现
Regex match pair ocurrences of a specific character
我一直在尝试制作满足此条件的正则表达式:
- 该单词由字符a,b组成
- b个字符必须成对(连续或不连续)
例如:
- abb -> 已接受
- abab -> 已接受
- aaaa -> 拒绝
- baaab -> 已接受
到目前为止我得到了这个:([a]*)(((b){2}){1,})
如你所见,我对这件事知之甚少,这会检查成对,但它仍然接受 b 为奇数的单词。
您可以使用此正则表达式检查一些 a
s 和偶数 b
s:
^(?:a*ba*ba*)+$
这会查找 2 b
s 被某个数字(可能是 0)a
s 包围的 1 次或多次出现。
请注意,这将匹配 bb
(或 bbbb
、bbbbbb
等)。如果您不想这样做,最简单的方法是为 a
:
添加正向前瞻
^(?=b*a)(?:a*ba*ba*)+$
根据两个条件检查字符数组
虽然您可以使用regular expressions, it would be simpler to solve it by applying some conditional checks against your two rules against an Array of characters created with String#chars做到这一点。例如,使用 Ruby 3.1.2:
# Rule 1: string contains only the letters `a` and `b`
# Rule 2: the number of `b` characters in the word is even
#
# @return [Boolean] whether the word matches *both* rules
def word_matches_rules word
char_array = word.chars
char_array.uniq.sort == %w[a b] and char_array.count("b").even?
end
words = %w[abb abab aaaa baaab]
words.map { |word| [word, word_matches_rules(word)] }.to_h
#=> {"abb"=>true, "abab"=>true, "aaaa"=>false, "baaab"=>true}
正则表达式非常有用,但字符串操作通常更快且更容易概念化。这种方法还允许您添加更多规则或验证中间步骤,而不会增加很多复杂性。
可能有许多方法可以进一步简化,例如使用 Set or methods like Array#& or Array#-。但是,我对这个答案的目标是使代码(以及您尝试应用的编码规则)更易于阅读、修改和扩展,而不是使代码尽可能简约。
我一直在尝试制作满足此条件的正则表达式:
- 该单词由字符a,b组成
- b个字符必须成对(连续或不连续)
例如:
- abb -> 已接受
- abab -> 已接受
- aaaa -> 拒绝
- baaab -> 已接受
到目前为止我得到了这个:([a]*)(((b){2}){1,})
如你所见,我对这件事知之甚少,这会检查成对,但它仍然接受 b 为奇数的单词。
您可以使用此正则表达式检查一些 a
s 和偶数 b
s:
^(?:a*ba*ba*)+$
这会查找 2 b
s 被某个数字(可能是 0)a
s 包围的 1 次或多次出现。
请注意,这将匹配 bb
(或 bbbb
、bbbbbb
等)。如果您不想这样做,最简单的方法是为 a
:
^(?=b*a)(?:a*ba*ba*)+$
根据两个条件检查字符数组
虽然您可以使用regular expressions, it would be simpler to solve it by applying some conditional checks against your two rules against an Array of characters created with String#chars做到这一点。例如,使用 Ruby 3.1.2:
# Rule 1: string contains only the letters `a` and `b`
# Rule 2: the number of `b` characters in the word is even
#
# @return [Boolean] whether the word matches *both* rules
def word_matches_rules word
char_array = word.chars
char_array.uniq.sort == %w[a b] and char_array.count("b").even?
end
words = %w[abb abab aaaa baaab]
words.map { |word| [word, word_matches_rules(word)] }.to_h
#=> {"abb"=>true, "abab"=>true, "aaaa"=>false, "baaab"=>true}
正则表达式非常有用,但字符串操作通常更快且更容易概念化。这种方法还允许您添加更多规则或验证中间步骤,而不会增加很多复杂性。
可能有许多方法可以进一步简化,例如使用 Set or methods like Array#& or Array#-。但是,我对这个答案的目标是使代码(以及您尝试应用的编码规则)更易于阅读、修改和扩展,而不是使代码尽可能简约。