开发者

Regular Expression search/replace help needed, Python

One rule that I need is that if the last vowel (aeiou) of a string is before a character from the set ('t','k','s','tk'), then a : needs to be added right after the vowel.

So, in Python if I have the string "orchestras" I need a rule that will turn it into "orchestra:s"

edit: The (t, k, s, tk开发者_开发知识库) would be the final character(s) in the string


re.sub(r"([aeiou])(t|k|s|tk)([^aeiou]*)$", r"\1:\2\3", "orchestras")
re.sub(r"([aeiou])(t|k|s|tk)$",            r"\1:\2",   "orchestras")

You don't say if there can be other consonants after the t/k/s/tk. The first regex allows for this as long as there aren't any more vowels, so it'll change "fist" to "fi:st" for instance. If the word must end with the t/k/s/tk then use the second regex, which will do nothing for "fist".


If you have not figured it out yet, I recommend trying [python_root]/tools/scripts/redemo.py It is a nice testing area.


Another take on the replacement regex:

re.sub("(?<=[aeiou])(?=(?:t|k|s|tk)$)", ":", "orchestras")

This one does not need to replace using remembered groups.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜