简体   繁体   中英

Unclosed Character Class (Regex)

So, I have this semi-complex regex that is searching for all text in between two strings, then replacing it.

My search regex for this is:

(jump *[A-Z].*)(?:[^])*?([A-Z].*:)

This gives an Unclosed Character Class on the final closing bracket, which I have been struggling to solve. The regex seems to work as intended on RegexR ( http://regexr.com/?38k63 )

Could anyone provide some help or insight?

Thanks in advance.

The error is at here:

(jump *[A-Z].*)(?:[^])*?([A-Z].*:)
                   ^

In character class ^ is still a special character. It usually negates other characters when you place there. So escape it with \\\\ in Java.

Different regex engines will treat [^] differently. Some will assume that it's the beginning of a negative character class excluding ] and any characters up to the next ] in the pattern, (eg [^][] will match anything except ] and [ ). Other engines will treat as a empty negative character class (which will match anything). This is why some regex engines will work, and others report it as an error.

If you meant for it to match a literal ^ character, you'll have to escape it like this:

(jump *[A-Z].*)(?:[\^])*?([A-Z].*:)

Or better yet, just remove it from the character class (you'll still have to escape it because ^ has special meaning outside of a character class, too):

(jump *[A-Z].*)(?:\^)*?([A-Z].*:)

Or if you meant for it to match everything up to the next [AZ].*: , try a character class like this:

(jump *[A-Z].*)(?:[\s\S])*?([A-Z].*:)

And of course, because this is Java, don't forget that you'll need to escape the all the \\ characters in any string literals.

Problem seems here in use of [^] :

(jump *[A-Z].*)(?:[^])*?([A-Z].*:)
                   ^
-------------------|

Try this regex instead:

(jump *[A-Z].*)[\\s\\S]*?([A-Z].*:)

OR this:

(?s)(jump *[A-Z].*).*?([A-Z].*:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM