Irfan Bilaloğlu
Irfan Bilaloğlu

Reputation: 41

Regular Expression, words with different characters

I have been searching about it for about 3 hrs, now I'm stuck. Here is the problem:

I want to find 7 character word where only 4. and 6. chars are same

like:

^...(.).\1.$

but i don't want to find

aaaBaBa

all other chars must different than each other like:

asdBfBg

my question is similar to this one: Java: Regular expression where each character occurs 0-1 times

but my knowledge wasn't enough to work with Lookarounds (?<= and (?=, (?

Upvotes: 1

Views: 2698

Answers (2)

pguardiario
pguardiario

Reputation: 54984

Here's something that works, maybe there's a better way to do this though.

/
\b # word boundary
(\w) # any word char
(?!\1)(\w) # any word char except \1
(?!\1|\2)(\w) # any word char except \1 or \2
(?!\1|\2|\3)(\w) # etc...
(?!\1|\2|\3|\4)(\w)
\4 # 4th capture
(?!\1|\2|\3|\4\5)(\w)
\b # word boundary
/x

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149000

Perhaps you can use a negative assertion, like this:

^(.)(.)(.)(.)(.)\4(.)(?<!(?:\1.*\1|\2.*\2|\3.*\3|\4.*\4.*\4|\5.*\5|\6.*\6).*)$

This will find any 7-letter word with the 4th and 6th letters the same, and whose 1st, 2nd, 3rd, 5th, or 7th (\6) letter do not appear twice, and whose 4th letter is not repeated three times.

Upvotes: 1

Related Questions