Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - It is possible to match a character repetition with regex? How?

Question:
Is is possible, with regex, to match a word that contains the same character in different positions?

Condition:
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.

Examples:
using lowercase 6char words I'd like to match words where the 3rd and the 4th chars are the same.

parrot <- match for double r
follia <- match for double l 
carrot <- match for double r
mattia <- match for double t
rettoo <- match for double t
melone <- doesn't match

I can't use the quantifier [d]{2} because it match any succession of two chars, and what if I say the 2nd and the 4th position instead of 3rd and 4th?

Is it possible to do what I want with regex? If yes, how can I do that?

EDIT:
Ask asked in the comments, I'm using python

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use a backreference to do this:

(.)1

This will match consecutive occurrences of any character.


Edit???Here’s some Python example:

import re

regexp = re.compile(r"(.)1")
data = ["parrot","follia","carrot","mattia","rettoo","melone"]

for str in data:
    match = re.search(regexp, str)
    if match:
        print str, "<- match for double", match.group(1)
    else:
        print str, "<- doesn't match"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...