简体   繁体   中英

Regex to match a double quoted string in Python

I am trying to grab the value after a string value like "Title" using regex in Python.

This is what I have so far:

re.compile(r'[\n\r].*"title":\s*([^\n\r]*)')

The problem I'm running into is it returns: [ ].

My goal is to return the Job Title from this string:

[{"title": "Inventory Accountant", "location": "Bern, KS", "snippet": "JOB PURPOSE

Any help would be much appreciated.

this is maybe not what you are looking for, but it may prove helpful as an alternative solution.

Is your string containing a list of dict? (Because it seems like so)

If that is the case, then you can load it as JSON and avoid REGEX all along. Remember to remove the '[' and ']' from the begging & end of the string.

The following example:

import json
txt = '[{"title": "Inventory Accountant", "location": "Bern, KS", "snippet": "JOB PURPOSE"}]'

data = json.loads(txt[1:-1])
print(data['title'])

Should return Inventory Accountant

I don't know if regular expressions are the best solution in this situation. Instead, you can try accessing the "title" key from the dictionary as said in the above answer.

However, if you need to use a regular expression , here is an example:

import re

string = '[{"title": "Inventory Accountant", "location": "Bern, KS", "snippet": "JOB PURPOSE"'

test = re.search(r'"title"\:(?P<val>.*?),', string)
value = test.group("val").strip()

print(value)

This returns the following value: "Inventory Accountant"

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