Search for words in quotation marks

1

I need to take the word and the two bold numbers of a string to pass it to an array so I can select it later. I've thought about regular expressions in python using the re class but I can not find the form

('{"id": 192, "result": [" on ", " 50 ", " 16777215 "] } \ r \ n ', (0,' \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 '))

The solution would be something like:

import re
Palabras[] = re.split(**PATRON_QUE_ME_FALTA**, Frase)
    
asked by Jose 28.12.2017 в 20:43
source

2 answers

1

If you always have a tuple in which the first element is a string of the form:

  

'{.., "result": something, ...}'

Then you have the valid representation of a Python dictionary and in this case you do not need regular expressions, you can use the method ast.literal_eval , safe version of eval :

>>> from ast import literal_eval

>>> datos = ('{"id":192, "result":["on","50","16777215"]}\r\n', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'))
>>> diccionario = literal_eval(datos[0])
>>> palabras = diccionario["result"]

In this case palabras is a list since '["on","50","16777215"]' is the valid representation of a Python list, we can access its elements through indexing, traverse it with a for , etc:

>>> palabras
['on', '50', '16777215']
>>> palabras[0]
'on'
>>> palabras[1]
'50'
>>> palabras[2]
'16777215'
    
answered by 28.12.2017 / 21:34
source
1

You can try with:

(?:'.*?')|(?:\".*?\")

This pattern satisfies the letters or numbers that are in quotes. To use it in Python you can try the following:

import re
frase = '"on", "50", "16777215" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"'
re.findall(r"(?:'.*?')|(?:\".*?\")", frase)

With this code we get a list of the words that the employer satisfies:

['"on"', '"50"', '"16777215"', '"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"']
    
answered by 28.12.2017 в 21:16