简体   繁体   中英

Java regex to match (group of words) subclass of (group of words)

I would like to write a regular expression in Java to match a sequence of word characters and spaces followed by the sequence of characters "subclass of" a sequence of word characters and spaces:

Example strings which should be matched:

a subclass of b

a and b subclass of c

a and b subclass of c and d

The following strings should not be matched:

subclass of

a subclass of

subclass of b

a subclass of b subclass of c

I tried the following regex:

    [a-zA-Z0-9 ]+subclass of[a-zA-Z0-9 ]+

(?:(?!subclass of).)+subclass of(?:(?!subclass of).)+

but they both fall short of what I need.

You can use this regex:

^\\w+(?:\\s+and\\s+\\w+)?\\s+subclass\\s+of\\s+\\w+(?:\\s+and\\s+\\w+)?$

Here is the Live Demo :

I'd make a little bit modification of your regex @anubhava:

^\\w+(?:\\sand\\s\\w+)*\\ssubclass\\sof\\s\\w+(?:\\sand\\s\\w+)*$

To make sure that the group of (and \\w+) can be matched more than once.

Live demo: here

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