In java, I'm trying to detect strings of the form: optional underline, capital letters, and then curly brackets encasing two parameters. I.e. things like MAX{1,2}
FUNC{3,7}
_POW{9,10}
在java中,我试图检测表单的字符串:可选的下划线,大写字母,然后是包含两个参数的大括号。即像MAX {1,2} FUNC {3,7} _POW {9,10}这样的东西
I've decided to put off dealing with the parameters until later, so the regex I'm using is:
我决定推迟处理这些参数,所以我使用的正则表达式是:
_?[A-Z]+//{.*//}
But I'm getting the following error when trying to compile it into a Pattern object:
但是在尝试将其编译为Pattern对象时,我收到以下错误:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 9
_?[A-Z]+//{.*//}
^
Anyone know what the problem is?
谁知道问题是什么?
2 个解决方案
#1
19
You need to escape the curly brackets in your expression, else they are treated as a repetition operator. I think you'd want to use \
for this instead of //
.
您需要转义表达式中的大括号,否则它们将被视为重复运算符。我想你想用\而不是//。
#2
4
John is correct. But you also don't want to use the '.*'
greedy-dot-star. Here is a better regex:
约翰是对的。但你也不想使用'。*'贪婪点星。这是一个更好的正则表达式:
Pattern regex = Pattern.compile("_?[A-Z]+\\{[^}]+\\}");
Note that you do NOT need to escape the curly brace inside a character class. This is fundamental syntax which you need to learn if you want to use regex effectively. See: regular-expressions.info - (an hour spent here will pay for itself many times over!)
请注意,您不需要在字符类中转义大括号。如果您想有效地使用正则表达式,这是您需要学习的基本语法。请参阅:regular-expressions.info - (这里花了一个小时就可以多付费!)
#1
19
You need to escape the curly brackets in your expression, else they are treated as a repetition operator. I think you'd want to use \
for this instead of //
.
您需要转义表达式中的大括号,否则它们将被视为重复运算符。我想你想用\而不是//。
#2
4
John is correct. But you also don't want to use the '.*'
greedy-dot-star. Here is a better regex:
约翰是对的。但你也不想使用'。*'贪婪点星。这是一个更好的正则表达式:
Pattern regex = Pattern.compile("_?[A-Z]+\\{[^}]+\\}");
Note that you do NOT need to escape the curly brace inside a character class. This is fundamental syntax which you need to learn if you want to use regex effectively. See: regular-expressions.info - (an hour spent here will pay for itself many times over!)
请注意,您不需要在字符类中转义大括号。如果您想有效地使用正则表达式,这是您需要学习的基本语法。请参阅:regular-expressions.info - (这里花了一个小时就可以多付费!)