Scala正则表达式需求:限制A/H连续次数及5字符内数量规则
Hey there! Let's work through this regex problem you're dealing with in Scala. I see you've already got a regex that handles rule 1 (no three consecutive As or Hs), so let's figure out how to integrate rule 2 properly.
First, let's recap the rules to make sure we're on the same page:
- Rule 1: No three consecutive As (
AAA) or Hs (HHH) anywhere in the string. - Rule 2: Every 5 consecutive characters must contain exactly 2 As and 3 Hs, or 3 As and 2 Hs. That means we can't have any 5-character stretch with 0, 1, 4, or 5 As (and corresponding H counts).
Now, here's a key insight: Your existing rule 1 already eliminates most of the invalid cases for rule 2. For example, any 5-character string with 0 As (all Hs: HHHHH) has three consecutive Hs, so rule 1 blocks it. Similarly, 5 As (AAAAA) has three consecutive As, which rule 1 also blocks. The same goes for 1-A strings like AHHHH or HAHHH (they have three consecutive Hs) and 4-A strings like AAAAH or AAAHA (they have three consecutive As).
The only rule 2 violations that slip past rule 1 are two specific 5-character patterns:
HHAHH: 1 A, no three consecutive Hs (so rule 1 allows it, but it violates rule 2)AAHAA: 4 As, no three consecutive As (again, rule 1 allows it, but rule 2 doesn't)
So we just need to add a check to exclude these two patterns alongside your existing rule 1 check. Here's the combined regex:
val validAHPattern = """^(?!.*(AAA|HHH))(?!.*(HHAHH|AAHAA))[AH]+$""".r
Let's break down what each part does:
^(?!.*(AAA|HHH)): This is your original rule 1 check—negative lookahead to ensure no three consecutive As or Hs exist in the string.(?!.*(HHAHH|AAHAA)): A second negative lookahead to block the two remaining rule 2 violations that rule 1 doesn't catch.[AH]+$: Ensures the entire string is made up of only As and Hs (no other characters) and has at least one character.
You can use this regex in Scala like this:
// Test valid string val validStr = "AHAHAHAHHAHAAHHAAHHAAHAHHAHAHAHAHAHAHA" println(validAHPattern.matches(validStr)) // Outputs true // Test string violating rule 1 (has HHH) val invalidRule1 = "AHAHAHAHHAHAAHHAAHHAAHAHHAHAHAHAHAHHHA" println(validAHPattern.matches(invalidRule1)) // Outputs false // Test string violating rule 2 (has HHAHH) val invalidRule2 = "HHAHHAAHHAHAAHHAAHHAAHAHHAHAHAHAHAHHAH" println(validAHPattern.matches(invalidRule2)) // Outputs false
This should cover both rules perfectly! Let me know if you run into any edge cases or need further tweaks.
内容的提问来源于stack exchange,提问作者Burnett

