java 这个正则表达式有什么问题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5524523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's wrong with this Regular Expression?
提问by Moshe
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?
有谁知道问题是什么?
回答by John Zwinck
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 //
.
您需要对表达式中的大括号进行转义,否则它们将被视为重复运算符。我想你会想用\
这个而不是//
.
回答by ridgerunner
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 manytimes over!)
请注意,您不需要对字符类中的花括号进行转义。如果您想有效地使用正则表达式,这是您需要学习的基本语法。请参阅:regular-expressions.info- (在这里度过了一个小时将支付本身许多在次!)