Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

java - 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.

question from:https://stackoverflow.com/questions/65540869/trying-to-convert-plural-words-into-singular-but-it-deletes-any-s

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...