METİN
METİN

Reputation: 13

How to match and replace specified last letter(s) of words with a different letter in a sentence

I read from a text file.

My sentence is: tax mass plus match

When I try that expression and code.

Actual output: taes maeses plues mateses

Expected output: taxes masses pluses matches

String line_2 = Files.readAllLines(Paths.get("input.txt.txt")).get(0);
Pattern pattern_Plural = Pattern.compile("\\b*[(ss)(s)(sh)(ch)(s)(x)(z)]", Pattern.CASE_INSENSITIVE);

Matcher m_Plural = pattern_Plural.matcher(line_2);

if (m_Plural.find()) {
   String str1 = m_Plural.replaceAll("es");
   System.out.println(str1);
}

Upvotes: 1

Views: 58

Answers (1)

Hülya
Hülya

Reputation: 3433

Try this:

String line_2 = Files.readAllLines(Paths.get("input.txt.txt")).get(0);
System.out.println(line_2.replaceAll("(?i)(ss|s|sh|ch|s|x|z)(\\b)", "$1es"));

$1 represents the captured group helps to keep the (ss|s|sh|ch|s|x|z) part of the text.

(?i) is used for case insensitivity.

Output:

taxes masses pluses matches

Upvotes: 1

Related Questions