[英]regex or string parsing
I am trying to parse a string which has a specific pattern. 我正在尝试解析具有特定模式的字符串。 An example valid string is as follows:
有效字符串示例如下:
<STX><DATA><ETX>
<STX>A?123<ETX>
<STX><DATA><ETX>
<STX>name!xyz<ETX>
<STX>age!27y<ETX>
<STX></DATA><ETX>
<STX>A?234<ETX>
<STX><DATA><ETX>
<STX>name!abc<ETX>
<STX>age!24y<ETX>
<STX></DATA><ETX>
<STX>A?345<ETX>
<STX><DATA><ETX>
<STX>name!bac<ETX>
<STX>age!22y<ETX>
<STX></DATA><ETX>
<STX>OK<ETX>
<STX></DATA><ETX>
this data is sent by device. 该数据由设备发送。 All I need is to parse this string with id:123 name:xyz, age 27y.
我所需要做的就是解析ID为123的字符串,名称为:xyz,年龄27y。
I am trying to use this regex: 我正在尝试使用此正则表达式:
final Pattern regex = Pattern.compile("(.*?)", Pattern.DOTALL); 最终的模式regex = Pattern.compile(“(。*?)”,Pattern.DOTALL);
this does output the required data : 这不会输出所需的数据:
<ETX>
<STX>A?123<ETX>
<STX><DATA><ETX>
<STX>name!xyz<ETX>
<STX>age!27y<ETX>
<STX>
How can I loop the string recursively to copy all into list of string. 我如何递归循环字符串以将全部复制到字符串列表中。 I am trying to loop over and delete the extracted pattern but it doesn't delete.
我正在尝试遍历并删除提取的模式,但不会删除。
final Pattern regex = Pattern.compile("<DATA>(.*?)</DATA>", Pattern.DOTALL);// Q?(.*?)
final StringBuffer buff = new StringBuffer(frame);
final Matcher matcher = regex.matcher(buff);
while (matcher.find())
{
final String dataElements = matcher.group();
System.out.println("Data:" + dataElements);
}
}
Are there any beter ways to do this. 有没有更好的方法可以做到这一点。
This is the output I am currently getting: 这是我当前得到的输出:
Data:<DATA><ETX><STX>A?123<ETX><STX><DATA><ETX><STX>name!xyz<ETX><STX>age!27y<ETX><STX> </DATA>
Data:<DATA><ETX><STX>name!abc<ETX><STX>age!24y<ETX><STX></DATA>
Data:<DATA><ETX><STX>name!bac<ETX><STX>age!22y<ETX><STX></DATA>
I am missing the A?234 and A?345 in the next two matches. 在接下来的两场比赛中,我缺少A?234和A?345。
I really dont know what exactly you want to achieve by this but if you want to remove the occurances of that pattern this line: 我真的不知道您希望通过此实现什么,但是如果您想删除该模式的出现,请执行以下操作:
buff.toString().replace(dataElements, "")
doesn't look good. 看起来不好。 you are just editing the string representation of that buff.
您只是在编辑该增益的字符串表示形式。 You have to again replace the edited version back into the buff (after casting).
您必须再次将编辑后的版本放回抛光机中(铸造后)。
使用此正则表达式解决了我的问题:
<STX>(A*)(.*?)<DATA>(.*?)</DATA>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.