热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java中的困难正则表达式,需要建议-DifficultRegexinJava,needadvice

ImtryingtomakeaRegexinJavathatcanparsethefollowingStrings我试图在Java中制作一个可以解析以下字符串的正则表达式

Im trying to make a Regex in Java that can parse the following Strings

我试图在Java中制作一个可以解析以下字符串的正则表达式

g1(g2,g2),g1(g2)

g1(g2(g3,g3),g2),g1(g2)

g1(g2)

I have been trying for hours but I cant make one that can split each example in the following classes.

我已经尝试了几个小时,但我不能制作一个可以拆分以下类中的每个示例。

    public class G1{

      List list;
    }

    public class G2{

      String g2;
      Set g3;
    }

Where I need one instance of g1 for each of the groups.

我需要为每个组提供一个g1实例。

Thanks

谢谢

EDIT

编辑

Fixed the classes.

修正了这些课程。

2 个解决方案

#1


1  

It looks like you have a grammar to deal with, regular expressions is not really the appropriate tool to do it, instead you're better off building a simple finite state machine to do the parsing.

看起来你有一个语法要处理,正则表达式并不是真正适合它的工具,相反,你最好建立一个简单的有限状态机来进行解析。

Another option which I don't recommend for something this simple is to use ANTLR which is a tool that is designed to do this sort of parsing. I don't recommend it because it would be overkill for the job.

另一个我不推荐的选项是使用ANTLR,这是一种专门用于进行此类解析的工具。我不推荐它,因为这对工作来说太过分了。

#2


1  

Regex is not a tool that handles recursion well.

正则表达式不是一个很好地处理递归的工具。

For instance, it can't easily discern that the outer parentheses is the one you want in this line

例如,它不能轻易地辨别外括号是你想要的那一行

g1(g2(g3,g3),g2),g1(g2)

G1(G2(G3,G3),G2),G1(G2)

If you try to use a greedy regex, it would go collect the whole line g1(g2(g3,g3),g2),g1(g2). If you try to go for non-greedy, it would collect g1(g2(g3,g3). Regexes that might gather it are pretty shaky and can break pretty easy.

如果你试图使用贪婪的正则表达式,它将收集整行g1(g2(g3,g3),g2),g1(g2)。如果你试图去非贪婪,它会收集g1(g2(g3,g3)。可能收集它的正则表达式非常不稳定,并且可以很容易地破解。

If the outer group is always called g1 and g1 is never nested within another group, you might be able to use something like this

如果外部组总是被称为g1而g1永远不会嵌套在另一个组中,那么您可以使用类似的东西

g1\(.*?\)(?=,g1|$)

Really though, regex is not a tool for this task.

实际上,正则表达式不是这项任务的工具。


推荐阅读
author-avatar
手机用户2502937963
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有