Korhan Aladag
Korhan Aladag

Reputation: 13

Trying to convert plural words into singular but it deletes any 's'

Trying to convert plural words into singular in Java for example foxes into fox but something is wrong that it deletes any 's'

File Reader function as follows:

public static String readFileAsString(String fileName) throws Exception {
    String data = "";
    data = new String(Files.readAllBytes(Paths.get(fileName)));
    return data;
}

Singularity converter function as follows;

public static String singular(String data) {
    Pattern pattern = Pattern.compile("");
    if (Pattern.matches("(/ss)$", data)) {
        data = data.replaceAll("(s|es)", (" "));
    } else {
        data = data.replaceAll("(s|es)", (" "));
    }

    return data;
}

Actually I'm aware that i shouldn't be using Pattern pattern = Pattern.compile(""); But I'm not sure how to use it.

Upvotes: 1

Views: 191

Answers (1)

Andreas
Andreas

Reputation: 159175

Seems you want a simple solution that looks for s or es at the end of a word, and removes them.

To do that, you need to ensure that the found s or es is at the end of a word, i.e. at least one letter before, and no letters after. For that, use the \b word boundary and \B non-word boundary patterns.

Instead of (s|es) you should use optional e followed by s, i.e. e?s

data = data.replaceAll("\\Be?s\\b", "");

Example

String data = "The quick brown foxes jumps over the lazy dogs";
data = data.replaceAll("\\Be?s\\b", "");
System.out.println(data);

Output

The quick brown fox jump over the lazy dog

Notice how the flawed premise of the code (that all words ending with s are plural words) also changes jumps to jump.

Upvotes: 1

Related Questions