Best way to code this, string to map conversion in Groovy

后端 未结 8 2010
情深已故
情深已故 2020-12-31 07:22

I have a string like

def data = \"session=234567893egshdjchasd&userId=12345673456&timeOut=1800000\"

I want to convert it to a map

8条回答
  •  不思量自难忘°
    2020-12-31 08:10

    If you're looking for efficient, regular expressions are where it's at:

    def data = "session=234567893egshdjchasd&userId=12345673456&timeOut=1800000"
    def map = [:]
    data.findAll(/([^&=]+)=([^&]+)/) { full, name, value ->  map[name] = value }
    
    println map
    

    prints:

    [session:234567893egshdjchasd, userId:12345673456, timeOut:1800000]
    

    If you're not familiar with regular expressions, it might look a little foreign, but it's really not that complicate. It just has two (groups), the first group is any character but a "&" or a "=". The second group is any character besides a "=". The capture groups are on either side of a "=".

提交回复
热议问题