Android Question [solved]regex question

Maodge

Member
Licensed User
hi,
i test my regex on web https://regex101.com (javascript)
realize a function ,get all strings between "{" and "}" from a file.
it works OK, and matched all. see attached pic

but when i use it inB4A, it does not work.
B4X:
    s1 = File.ReadString(File.DirAssets,"songgrouplist.txt")

    matcher1=Regex.Matcher("{[\s]*.*[\s]*.*[\s]*.*[\s]*.*[\s]*.*[\s]*}",s1) 'here program crash
    Do While matcher1.Find
        mystrings = matcher1.Match
    Loop
what's the problem?
Thanks
 

Attachments

  • 03.png
    03.png
    234.6 KB · Views: 413
  • test-regex-02.zip
    7.3 KB · Views: 419
  • songgrouplist.txt
    653 bytes · Views: 413
Last edited:

Roycefer

Well-Known Member
Licensed User
Longtime User
You have to escape the curly bracket {} characters. Also, this pattern is too fragile, verbose and redundant. It can be shortened to "\{(?:\s*.*){5}\s*\}" if you need to find items with exactly 5 elements. If you just want anything inside curly brackets, you can achieve the same result with "\{.*?\}" (make sure to replace the newline characters).

Furthermore, did you create this text file? If so, you are probably better off using the JSON library to create JSON and then parse it. It will be much easier and more robust. Your songgrouplist.txt file is not valid JSON but it's close enough that you should have just used JsonGenerator to create it and the JsonParser to parse it.
 
Upvote 0

Maodge

Member
Licensed User
You have to escape the curly bracket {} characters. Also, this pattern is too fragile, verbose and redundant. It can be shortened to "\{(?:\s*.*){5}\s*\}" if you need to find items with exactly 5 elements. If you just want anything inside curly brackets, you can achieve the same result with "\{.*?\}" (make sure to replace the newline characters).

Furthermore, did you create this text file? If so, you are probably better off using the JSON library to create JSON and then parse it. It will be much easier and more robust. Your songgrouplist.txt file is not valid JSON but it's close enough that you should have just used JsonGenerator to create it and the JsonParser to parse it.
Thanks for your suggestion. I think it is a good idea. I will try to use it in my project.

and I test \{(?:\s*.*){5}\s*\} on web https://regex101.com/ ,this is ok
and in prgram is OK.
Problem is in B4A regex pattern "{" "}" should add "\" like "\{" "\}"
 
Upvote 0
Top