Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

Regex search string contains with specific count of letter

I am trying to workout the regex for searching string which satisfies count of letters where not in specific order

such as:

AAABBBCCCDDD
BBBAAADDDCCC
CCCAAABBBDDD

are TRUE:

so far, I have got A{3}B{3}C{3}D{3} would matches the first line, but for other lines would be needing different order.

is there any great solution that would work out?

question from:https://stackoverflow.com/questions/65835493/regex-search-string-contains-with-specific-count-of-letter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can match and capture a letter, then backreference that captured character. Repeat the whole thing as many times as needed, which looks to be 4 here:

(?:([A-Z])1{2}){4}

https://regex101.com/r/vrQVgD/1

If the same character can't appear as a sequence more than once, I don't think this can be done in such a DRY manner, you'll need separate capture groups:

([A-Z])1{2}(?!1)([A-Z])2{2}(?!1|2)([A-Z])3{2}(?!1|2|3)([A-Z])4{2}

https://regex101.com/r/vrQVgD/2

which is essentially 4 of a variation on the below put together:

(?!1|2|3)([A-Z])4{2}

The (?!1|2|3) checks that the next character hasn't occurred in any of the previously matched capture groups.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...