0

I am trying to remove the letter 's' from the end of any string that follows this rule:

There must be a vowel somewhere in the word that isn't in the second to last location. There can be a vowel in the second to last position in the string, but the 's' will not be removed if the only vowel is in the second to last position.

For example:

gas -> would not get changed because the only vowel 'a' is in the position right before the 's'

toys -> would become 'toy'

examples -> example because there is a vowel (e,a) in the word before the s, and not only in the second to last position.

Now I have a method in a class class called Tokenizer.java

public String remove(String word){

        //replace any words that end with s if the preceding word part contains a vowel not immediately before the 's'                                                                                   
        word.replaceAll("(?i)([aeiou][a-z]*[a-rt-z])s\\b", "$1");   

        return word; 
}

and I call this method in my tester.java class package tokenizer;

public class Tester {

    public static void main(String[] args) { 

        String word = token.deleteS("causes"); 
        System.out.println(word);
        word = token.remove("examples"); 
        System.out.println(word);
        word = token.deleteS("toys"); 
        System.out.println(word);
        word = token.deleteS("gas"); 
        System.out.println(word);

    }

}

my output:

causes
examples
toys
gas

expected output:

cause
example
toy
gas

The issue I am having is that when I test it on this regex 101 link, I see that it is working. Why is it acting differently in java?

Anderology
  • 147
  • 1
  • 2
  • 9

2 Answers2

1

You should replace following line in your method

word.replaceAll("(?i)([aeiou][a-z]*[a-rt-z])s\\b", "$1");    

with

word = word.replaceAll("(?i)([aeiou][a-z]*[a-rt-z])s\\b", "$1"); 

or remove it and leave this as body of function

return word.replaceAll("(?i)([aeiou][a-z]*[a-rt-z])s\\b", "$1"); 

methods of string function doesn't affect string itself just return result as string so you need to intercept this new string by assigning it to same or new variable

MoreThanChaos
  • 2,054
  • 5
  • 20
  • 40
0

Try this:

public String remove(String word){

        return word.replaceAll("(?i)([aeiou][a-z]*[a-rt-z])s\\b", "$1");  

}
Blue Boy
  • 620
  • 1
  • 6
  • 13