3

I have been trying to come up with a regex for the following string:

[1,null,"7. Mai 2017"],[2,"test","8. Mai 2018"],[3,"test","9. Mai 2019"]

I am trying to get as match output each bracket with its content as a single element like the following:

[1,null,"7. Mai 2017"]
[2,"test","8. Mai 2018"]
[3,"test","9. Mai 2019"]

My initial naive approach was something like this:

(\[[^d],.+\])+

However, the .+ rule is too general and ends up matching the whole line. Any hints?

7
  • 1
    Where is the string coming from? Is this a JSON string? Note that adding [ and ] from the beginning and the end of the string would make this particular string JSON loadable with json.loads().. Commented May 8, 2017 at 17:52
  • You can use r'\[[^]]*]' Commented May 8, 2017 at 17:53
  • 1
    I think you can also use ast.literal_eval() Commented May 8, 2017 at 17:54
  • @dot.Py the null would probably need to be special-handled then.. Commented May 8, 2017 at 17:57
  • @alecxe thanks for your info! so according to docs, the ast.literal_eval() works with None but don't works with Null.. Commented May 8, 2017 at 18:00

3 Answers 3

1

I am not sure about the data format you are trying to parse and where it is coming from, but it looks JSON-like. For this particular string, adding square brackets from the beginning and the end of the string makes it JSON loadable:

In [1]: data = '[1,null,"7. Mai 2017"],[2,"test","8. Mai 2018"],[3,"test","9. Mai 2019"]'

In [2]: import json

In [3]: json.loads("[" + data + "]")
Out[3]: 
[[1, None, u'7. Mai 2017'],
 [2, u'test', u'8. Mai 2018'],
 [3, u'test', u'9. Mai 2019']]

Note how null becomes Python's None.

Sign up to request clarification or add additional context in comments.

Comments

1

The following code will output what you've requested using \[[^]]*].

import re
regex = r'\[[^]]*]'
line = '[1,null,"7. Mai 2017"],[2,"test","8. Mai 2018"],[3,"test","9. Mai 2019"]'
row = re.findall(regex, line)
print(row)

Output:

['[1,null,"7. Mai 2017"]', '[2,"test","8. Mai 2018"]', '[3,"test","9. Mai 2019"]']

Consider changing null to None as it matches python representation.

Comments

1

You might consider the wonderful module pyparsing to do this:

import pyparsing 

for match in pyparsing.originalTextFor(pyparsing.nestedExpr('[',']')).searchString(exp):
    print match[0]
[1,null,"7. Mai 2017"]
[2,"test","8. Mai 2018"]
[3,"test","9. Mai 2019"]

(Unless it is actually JSON -- use the JSON module if so...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.