Java中通过匹配字符串模式提取目标单词的简便方法
在Java中从固定模式字符串提取单词的简便方法
当然有啦!针对你这种固定模式的字符串提取需求,Java里有好几种简便的实现方式,我给你分享两个最常用的方案:
方法1:正则表达式(最灵活通用)
正则表达式是处理这类字符串匹配提取的首选,尤其是当你的模式可能有微小变化时,灵活性拉满。你只需要把原模式里的<topic1>和<topic2>换成正则的捕获组(\w+)(用来匹配单词字符),然后就能轻松提取目标内容:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class TopicExtractor { public static void main(String[] args) { // 把原模式的<topic1>和<topic2>替换为捕获组(\w+) String patternStr = "what do you know about (\\w+) and (\\w+)"; String input = "what do you know about cricket and football"; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(input); if (matcher.find()) { String topic1 = matcher.group(1); String topic2 = matcher.group(2); System.out.println(topic1 + ", " + topic2); // 输出:cricket, football } } }
如果你的话题可能包含空格(比如table tennis),可以把正则里的\w+换成非贪婪匹配的.+?,调整后的模式为what do you know about (.+?) and (.+),这样就能适配包含空格的话题内容了。
方法2:字符串替换+分割(适合超固定的简单模式)
如果你的模式是完全固定、不会有任何变体的,那用字符串替换加分割的方法会更简单直接,代码也更易懂:
public class TopicExtractor { public static void main(String[] args) { String fixedPrefix = "what do you know about "; String input = "what do you know about cricket and football"; // 先去掉固定前缀 String contentAfterPrefix = input.replaceFirst(fixedPrefix, ""); // 用" and "作为分隔符拆分内容 String[] topics = contentAfterPrefix.split(" and "); System.out.println(topics[0] + ", " + topics[1]); // 输出:cricket, football } }
这种方法不需要引入正则相关的类,代码更简洁,但只适合模式完全固定的场景,一旦模式有变化就需要修改代码中的前缀或分隔符。
内容的提问来源于stack exchange,提问作者ovi
相关产品推荐
相关产品推荐

