Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

java regex pattern unclosed character class

I need some help. Im getting:

Caused by: java.util.regex.PatternSyntaxException: Unclosed character class near index 24
^[a-zA-Z└-?0-9£μ /.'-]*$
                        ^
        at java.util.regex.Pattern.error(Pattern.java:1713)
        at java.util.regex.Pattern.clazz(Pattern.java:2254)
        at java.util.regex.Pattern.sequence(Pattern.java:1818)
        at java.util.regex.Pattern.expr(Pattern.java:1752)
        at java.util.regex.Pattern.compile(Pattern.java:1460)
        at java.util.regex.Pattern.<init>(Pattern.java:1133)
        at java.util.regex.Pattern.compile(Pattern.java:823)

Here is my code:

String testString = value.toString();

Pattern pattern = Pattern.compile("^[a-zA-Z300-3770-9u0153346 u002F.'-\]*$");
Matcher m = pattern.matcher(testString);

I have to use the unicode value for some because I'm working with xhtml.

Any help would be great!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that you want to match and - and not ]:

Pattern pattern = Pattern.compile("^[a-zA-Z300-3770-9u0153346 u002F.'\\-]*$");

You need to double escape your backslashes, as is also an escape character in regex. Thus \] escapes the backslash for java but not for regex. You need to add another java-escaped in order to regex-escape your second java-escaped .

So \\ after java escaping becomes \ which is then regex escaped to .

Moving - to the end of the sequence means that it is used as a character, instead of a range operator as pointed out by Pshemo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...