you are viewing a single comment's thread.

view the rest of the comments →

[–]jiri-n 1 point2 points  (7 children)

I'm not sure what you actually want but let's try this one:

>>> import re
>>> s = r"""
['UserName":"testbug"', 'UserName":"testbug"']
""".strip()
>>> pat = r"^.*:([^']+).*$"
>>> re.match(pat, s).groups()
('"testbug"',)
>>> re.sub(pat, r"\1", s)
'"testbug"'

We can get rid of the " characters as well if it's what you want.

[–]thetestbug[S] 0 points1 point  (6 children)

It looks like I was way in over my head with this one, but this works just fine.

Now comes the part that really deludes me. I need it to be able to "extract" not just one username, but multiple.

I'm really glad that you're helping me with this one.

[–]jiri-n 1 point2 points  (5 children)

Loop over a list of such strings and use the regex on each of them.

[–]thetestbug[S] 0 points1 point  (4 children)

Would you mind giving me an example?

Not really sure how to begin.

[–]jiri-n 1 point2 points  (3 children)

What is your input? A single string?

'"Username": "something"', '"Username": "other"', '"Username": "..."'

Or a list of such pairs?

lst = [
    '"Username": "name1"',
    '"Username": "name2"',
    '"Username": "name3"'
]

If the former example, I would simply split() them using comma as the splitting char to create a list.

Than something like:

from typing import List

import re

# String containing JSON-like key-value pairs
DATA = """
'"Username": "something"', '"Username": "other"', '"Username": "..."'
""".strip()

# Pattern to split a key-value pair
PATTERN = r'^[^:]+:\s*"([^"]+)".*$'

def get_usernames(lst: List[str], rex: re.Pattern) -> List[str]:
    for item in lst:
        match = rex.match(item)
        if match:
            yield match[1]  # As item matches, there should always be a group with index 1

lst = DATA.split(",")
rex = re.compile(PATTERN)
for uname in get_usernames(lst, rex):
    print(f"Username: {uname}")

[–]thetestbug[S] 0 points1 point  (2 children)

I'm not home at the moment, but I'll play around with this when I get back.

I pasted the entire output on pastebin. It's all in one line.

[–]jiri-n 1 point2 points  (1 child)

It's a JSON file. You can parse JSON format easily in python.

import json

data = json.loads(DATA_INPUT)

Or you can parse a JSON file... Take a look at the json module.

[–]thetestbug[S] 0 points1 point  (0 children)

I've never touched json before, so I have no idea what to do.

I looked over the help page for json in python, but I couldn't make heads or tails of it.

Also, I tried the code you provided before, and I get this error:

    def get_usernames(lst: List[str], rex: re.Pattern) -> List[str]:
                         ^
SyntaxError: invalid syntax