Java正则仅匹配首个单词问题及输出格式优化咨询
Let's break down and solve your two problems step by step:
1. Why only the first word is matched (and how to fix it)
The root cause here is how you're reading the input text. If you used scan.next() to capture the user's pasted text, that method only reads up to the first whitespace—so your text variable only holds "lorem" instead of the full "lorem ipsum dolor sit amet" string. That's why searching for "dolor" returns no match.
Fix:
Replace the code where you read the input text with scan.nextLine() instead of scan.next(). For example:
// When capturing the user's input text System.out.println("Paste your text here:"); String text = scan.nextLine(); // This reads the entire line including spaces
Also, in your searching() method, if you want to allow searching for phrases with spaces, use scan.nextLine() to read the search term too:
public void searching() { System.out.println("Enter the word/phrase you wish to find"); String searchTerm = scan.nextLine(); // Use nextLine() to capture phrases with spaces Pattern pattern = Pattern.compile(searchTerm); Matcher matcher = pattern.matcher(text); // ... rest of your code }
2. Modify output to show full text with matched words in uppercase
Instead of printing index positions, you can use the Matcher.replaceAll() method to replace all matched occurrences with their uppercase version, then print the modified full text.
Updated searching() method:
public void searching() { System.out.println("Enter the word you wish to find"); String searchTerm = scan.nextLine(); Pattern pattern = Pattern.compile(searchTerm); Matcher matcher = pattern.matcher(text); if (matcher.find()) { // Replace all matches with uppercase and print the full text String modifiedText = matcher.replaceAll(matchResult -> matchResult.group().toUpperCase()); System.out.println("Modified text with matches in uppercase:\n" + modifiedText); } else { System.out.println("No match found."); } }
Example output:
If your input text is "lorem ipsum dolor sit amet" and you search for "dolor", the output will be:
Modified text with matches in uppercase: lorem ipsum DOLOR sit amet
内容的提问来源于stack exchange,提问作者user14252942

