Ina06
Ina06

Reputation: 1

Regex in Java - Regular Expression

I have a problem in Regular expression. I need to print and count the words starts with word ‘ge’ and end with either word ‘ne’ or ‘me’. When I running the code only words start with "ge" appear. Can anyone help me to improve my source code?

Pattern p = Pattern.compile("ge\\s*(\\w+)");
Matcher m = p.matcher(input);

int count=0;
List<String> outputs = new ArrayList<String>();

while (m.find()) {
    count++;
    outputs.add(m.group());
    System.out.println(m.group());
}

System.out.println("The count is " + count);

Upvotes: 0

Views: 104

Answers (2)

d0nut
d0nut

Reputation: 2834

Well you're kinda missing the second half of your regex

ge\s*(\w+)[nm]e

This will work.

Regex101

Upvotes: 0

vks
vks

Reputation: 67988

\bge\w*[nm]e\b

This should do it for you.

In java this would be

\\bge\\w*[nm]e\\b

use \b to denote word boundary

Upvotes: 1

Related Questions