SachiraChin
SachiraChin

Reputation: 570

Find words only containing given characters : RegEx

I have set of words. For example,

abc, adb, acb, cab, abcc, abk, bacc

I want to find words which only have

abc

so, result I need is

abc, acb, cab, abcc, bacc

I need to find this using Regular Expressions.
Can anyone please help me.

Upvotes: 4

Views: 6083

Answers (3)

FailedDev
FailedDev

Reputation: 26930

The regex below will find all your words only with abc characters inside them.

Pattern regex = Pattern.compile("\\b[abc]+\\b");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    // matched text: regexMatcher.group()
    // match start: regexMatcher.start()
    // match end: regexMatcher.end()
} 

Upvotes: 4

Håvard
Håvard

Reputation: 10080

\\b[abc]+\\b

or

\\b[a-c]+\\b

[ and ] denotes a character set, and + means 1 or more repetitions of any character within the set. \b is word boundary, so you will only match full words.

Example.

Upvotes: 0

user834595
user834595

Reputation:

Not worrying about case for a simple example

[a-c]+

will match any combination of one-or-more letters from a-c

[afz]+

would do the same for a,f,z

As well as considering case, you'd also want to consider what constitues a 'word' (preceded and succeeded by whitespace or whatever)?

Upvotes: 3

Related Questions