parsing string with specific name in python
Question: i have string like this

    
    
    <name:john student male age=23 subject=\computer\sience_{20092973}>
    

i am confused ":","="

i want to parsing this string!

so i want to split to list like this

    
    
    name:john
    job:student
    sex:male
    age:23
    subject:{20092973}
    

parsing string with specific name(name, job, sex.. etc) in python

i already searching... but i can't find.. sorry..

how can i this?

thank you.


Answer: It's generally a good idea to give more than one example of the strings you're
trying to parse. But I'll take a guess. It looks like your format is pretty
simple, and primarily whitespace-separated. It's simple enough that using
regular expressions should work, like this, where `line_to_parse` is the
string you want to parse:

    
    
    import re
    matchval = re.match("<name:(\S+)\s+(\S+)\s+(\S+)\s+age=(\S+)\s+subject=[^\{]*(\{\S+\})", line_to_parse)
    matchgroups = matchval.groups()
    

Now matchgroups will be a tuple of the values you want. It should be trivial
for you to take those and get them into the desired format.

If you want to do many of these, it may be worth compiling the regular
expression; take a look at the `re` documentation for more on this.

As for the way the expression works: I won't go into regular expressions in
general (that's what the `re` docs are for) but in this case, we want to get a
bunch of strings that don't have any whitespace in them, and have whitespace
between them, and we want to do something odd with the subject, ignoring all
the text except the part between { and }.

Each "(...)" in the expression saves whatever is inside it as a group. Each
"\S+" stands for one or more ("+") characters that aren't whitespace ("\S"),
so "(\S+)" will match and save a string of length at least one that has no
whitespace in it. Each "\s+" does the opposite: it has not parentheses around
it, so it doesn't save what it matches, and it matches at one or more ("+")
whitespace characters ("\s"). This suffices for most of what we want. At the
end, though, we need to deal with the subject. "[...]" allows us to list
multiple types of characters. "[^...]" is special, and matches anything that
isn't in there. {, like [, (, and so on, needs to be escaped to be normal in
the string, so we escape it with \, and in the end, that means "[^{]*" matches
_zero_ or more ("*") characters that aren't "{" ("[^{]"). Since "*" and "+"
are "greedy", and will try to match as much as they can and still have the
expression match, we now only need to deal with the last part. From what I've
talked about before, it should be pretty clear what "({\S+})" does.

