简体   繁体   中英

Capture same line multiple times

Given text like,

A 0 1 2 3 4

I want to match the A with each number as a separate match like,

re.findall(some_regex, "A 0 1 2 3 4")

would return,

[
  ["A", "0"],
  ["A", "1"],
  ["A", "2"],
  ["A", "3"],
  ["A", "4"],
]
    dd ='A01234'
    Result = [[dd[0],j] for i,j in enumerate(dd) if i!=0]
    #Output = [['A', '0'], ['A', '1'], ['A', '2'], ['A', '3'], ['A', '4']]

That is not possible. But you can generate such a list easily.

x = re.findall("A*[0-9]", "A 0 1 2 3 4")
result = [["A", str(c)] for c in x]

Try this, I did it with two Python regex .

import re

text = "A 0 1 2 3 4"  # your text here

"""
select first character which belongs to alphabetically
between a and z, lower case OR upper case. If you need
to match only upper case character, just change pattern1
into "^[A-Z]"

pattern2 will match all the string contains with digits
which mean numbers from 0-9
"""
pattern1 = "^[A-Za-z]"
pattern2 = "\d"

print([[re.search(pattern1, text).group(0), a] for a in re.findall(pattern2, text)])

Output is,

[['A', '0'], ['A', '1'], ['A', '2'], ['A', '3'], ['A', '4']]

Now you can change first character as you wish with any number of digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM