Hi, I am learning how to use regex to split a word into syllables and then add a letter “p” and repetition after each syllable. If a syllable starts with a consonant(s), then the consonant(s) should be removed. In this case, the definition of syllable is zero or more consonants followed by a single vowel followed by zero or more consonants. For example, I have an input:
The expected output:Two peas in a pod
I have written this code, the only problem is that it does not allow spaces between words. May I ask suggestions to adjust the code? Thank youTwopo pepeaspas inpin apa podpod
Output:import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; // A syllable is defined as: zero or more consonants followed by a single vowel followed by zero or more consonants. // In this case, only {aeiou} are considered vowels. public class Language { public static void main(String[] args) { String input = "Two peas in a pod"; String addP = "p"; // Test whether the regular expression matches the pattern. Matcher m = Pattern.compile("([^aeiou]?[aeiou])((nghhgfdgy|[^aeiou])(?![aeiou]))?", Pattern.CASE_INSENSITIVE).matcher(input); int s = 0; // Find the next expression that matches the pattern. while (m.find()) { // If the first letter of syllable starts with a vowel, then add p before repetition if (input.charAt(m.start()) == 'a' || input.charAt(m.start()) == 'i' || input.charAt(m.start()) == 'o' || input.charAt(m.start()) == 'e' || input.charAt(m.start()) == 'u') { System.out.print(input.substring(s, m.end()).trim() + addP + input.substring(m.start(), m.end()).trim()); } // If the first letter of syllable starts with a consonant, then add p before repetition and remove the first letter of repetition else { System.out.print(input.substring(s, m.end()).trim() + addP + input.substring(m.start(), m.end()).substring(1).trim()); } s = m.end(); } } }
Twopopepeaspasinpinapapodpod