我想创建一个正则表达式,以便我可以使用以下约束在 Java 中拆分字符串:
Any non-word character, except for:
(a) Characters surrounded by ' '
(b) Any instance of := >= <= <> ..
对于以下示例字符串:
print('*'); x := x - 100
我可以在String[]
中得到以下结果:
print
(
'*'
)
;
x
:=
x
-
100
这是我目前拥有的正则表达式:
str.split("\\s+|"+
"(?=[^\\w'][^']*('[^']*'[^']*)*$)|" +
"(?<=[^\\w'])(?=[^']*('[^']*'[^']*)*$)|" +
"(?=('[^']*'[^']*)*$)|" +
"(?<=')(?=[^']*('[^']*'[^']*)*$)");
但这给了我以下结果:
print
(
'*'
)
;
x
:
= <!-- This is the problem. Should be above next to the :
x
-
100
更新
我现在了解到使用正则表达式不可能实现此目的。
但是,我仍然无法使用任何外部框架或词法分析器,并且必须使用包含的 Java 方法,例如 StringTokenizer。
最佳答案
免责声明:正则表达式不是通用解析器。如果您正在阅读的文本是一种具有嵌套结构的复杂语言,那么您需要使用实际的词法分析器,而不是正则表达式。例如。下面的代码支持“由 ' ' 包围的字符”,这是一个简单的定义,但如果字符可以包含转义的 '
字符,则需要一个词法分析器。
不要使用split()
。
如果您使用 find()
循环,您的代码将更容易阅读和理解。它也会表现得更好。
您编写正则表达式来指定您想要在 find()
循环的一次迭代中捕获的内容。您可以依靠 |
选择第一个匹配的模式,因此首先放置更具体的模式。
Pattern p = Pattern.compile("\\s+" + // sequence of whitespace
"|\\w+" + // sequence of word characters
"|'[^']*'" + // Characters surrounded by ' '
"|[:><]=" + // := >= <=
"|<>" + // <>
"|\\.\\." + // ..
"|."); // Any single other character
String input = "print('*'); x := x - 100";
for (Matcher m = p.matcher(input); m.find(); )
System.out.println(m.group());
输出
print
(
'*'
)
;
x
:=
x
-
100
关于Java 正则表达式 : Splitting based on multiple conditions with exceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39681158/