1

I'm attempting to count the number of syllables in a given word using regex. I've referred to some other posts on stack overflow but am getting strange behavior when I run my program.

Here is what I'm attempting

int n=0;
Pattern p = Pattern.compile("[aeiouy]+[^$e]");
Matcher m = p.matcher("Harry");

while(m.find()) {
     n++;
}

System.out.println(n);

Now, it's printing out 1. But there is both an "a" and "y" within the string. Where have I gone wrong?

1 Answer 1

2

At the end of the String there are no more letters to match so remove the expression [^$e]

Pattern p = Pattern.compile("[aeiouy]+");

Although from your comment you seem to want to treat e as a special case. You could do

Pattern p = Pattern.compile("[aiouy]|(?!^)e(?<!$)");
Sign up to request clarification or add additional context in comments.

4 Comments

The purpose of the [^$e] was to ignore any occurrences of "e" at the end of the String.
@ClownInTheMoon if that is what you want to do, you should be using [^e]$ instead of [^$e]. Also, [aeiouy]+ creates groups of one or more vowels because of the + at the end. I'm not sure if that is what you're looking for.
Intersting. When I use '[^e]$' then the value of 'n' comes out as zero. Yes I'm looking for groups of one or more vowels and then attempting to not count silent e's.
Possibly what you're really looking for is negative assertions. See the update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.