In Regex or Python: Count, add and write (Number of times it repeats + character name) and proceed … and in a new occurrence repeat the process

蹲街弑〆低调 提交于 2020-02-06 23:58:11

问题


Given the following list or tuple:

list: [UURRUULLLRRDDDBBBUUU]

Step 1: Count how many times an "U" character repeats before a new "unknown2 (R or D or B or L?)" character appears and records (number of repetitions + letter of the respective "U" character)

Step2: Continued from Step 1: Count how many times the "unknown2" character repeats until a new character other than "unknown2" appears. or equal to the "U" character and record (number of repetitions + letter of the respective "unknown2" character).

Intermediate Step: If the new character after the "unknown2" character equals the "U" character count how many times it repeats in this new occurrence and repeat Step1.

That is, for the tuple (list) the result of the organized repetitions of the way I want is:

2U2R2U3L2R3D3B3U

Something similar would be This (but not in regex) besides the result is not the same but it is a start for me.


回答1:


You may use

re.sub(r"(.)\1*", lambda x: "{}{}".format(len(x.group()), x.group(1)), text)

See the online demo

Details

  • (.)\1* is a pattern that matches and captures a char (other than a line break char, use re.DOTALL to also match line breaks) and then matches 0+ same chars as in Group 1.
  • lambda x: "{}{}".format(len(x.group()), x.group(1)) is the replacement where x is the found match object, and the return value is a concatenation of the length of the whole match (len(x.group())) and the char in Group 1 (x.group(1)).


来源:https://stackoverflow.com/questions/59557073/in-regex-or-python-count-add-and-write-number-of-times-it-repeats-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!