Reputation: 3147
I am trying to get groups which match the pattern. Input String is class equals
'one and two!' and 'three or four five' and 'six'
I have tried following pattern. But it matches and which is not within single quotes
(?:'(?:\S*\s*)*(and|or)+(?:\s*\S*)*')+
I want groups like
'one and two!'
'three or four five'
All String which has and|or within single quotes should be matched. within single quote it can have special characters and many spaces etc
How can i alter the pattern which i have above?
Upvotes: 0
Views: 80
Reputation: 121860
Provided there are no single quotes in your single quotes then you can use a pattern such as:
final Pattern PATTERN = Pattern.compile("('[^']+')( (and|or) )?");
You would then collect all matches in a list as such:
final List<String> matches = new ArrayList<>();
final Matcher m = PATTERN.matcher(input);
while (m.find())
matches.add(m.group(1));
If there are potential unescaped single quotes then this is not doable with regexes. If they can be escaped, then have a look here for a technique to write an efficient regex.
Upvotes: 1