正则表达式解析命令字符串 [英] Regex to parse a command string

查看:112
本文介绍了正则表达式解析命令字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String解析为java.util.Map的正则表达式是什么,其中String具有如下定义的格式:

What is the regex to parse a String into a java.util.Map where the String have a defined format like this:

message_type={any_text}&message_number={digits}&code={digits}&id={digits}&message={any_text}&timestamp={digits_with_decimal}

目标是生成一个具有message_type,message_number,code,id,message和timestamp键的Map.

The goal is to generate a Map with message_type, message_number, code, id, message and timestamp keys.

这是正则表达式可以解析的东西吗?还是需要带有语法的解析器?

Is this something that a regex can parse? Or this would need a parser with grammar?

更新:

这不是相同的URI解析问题.此处的消息是主体字符串,因此可能包含&"在消息部分.对&"使用相同的拆分可能会导致错误的分割.

This is not the same URI parsing problem. The message here is a body String thus may include '&' in the message part. Using the same split with '&' might cause a wrong split.

此外,{ }只是需要用正则表达式替换的理想函数.

Also, the { } are just the ideal function that needs to be replaced by the regex.

推荐答案

我认为关键是使用惰性评估,以下方法可以解决问题:

I think the key is to use lazy evaluation and the following should do the trick:

([a-zA-Z].*?={.*?})

从一个字母(下或上)开始,直到首次出现"=",然后获得包括括号在内的值并重复.

Start with a letter (lower or upper) till the first occurrence of "=" and then get the value including the braces and repeat.

演示: https://regex101.com/r/iE0hU3/1

这篇关于正则表达式解析命令字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆