如何在以%分隔的字符串中提取含指定关键词的短语?
简单解决方案:拆分+过滤+拼接
嘿,这个需求其实根本不用纠结复杂的lastIndexOf逻辑!用字符串拆分+短语过滤+结果拼接的思路就能轻松搞定,既能覆盖所有包含关键词的短语,代码还简洁易懂。
核心思路步骤
- 第一步:把原字符串按分隔符
%拆分成独立短语的数组,同时清理掉每个短语前后的多余空格(毕竟原字符串里的短语前后都带空格)。 - 第二步:筛选出数组中包含目标关键词的所有短语。
- 第三步:把筛选后的短语用
//连接成最终需要的新字符串。
代码示例(JavaScript)
const originalStr = " Where is my dog, john ? % your dog is on the table % really thanks john % you're welcome % Have a nice dog"; const keyword = "dog"; // 1. 按%拆分并清理每个短语的前后空格 const phrases = originalStr.split('%').map(phrase => phrase.trim()); // 2. 过滤出包含关键词的短语 const matchedPhrases = phrases.filter(phrase => phrase.includes(keyword)); // 3. 拼接成目标格式的字符串 const resultStr = matchedPhrases.join(' // '); console.log(resultStr); // 输出:"Where is my dog, john ? // your dog is on the table // Have a nice dog"
代码示例(Python)
如果用Python实现,思路完全一致:
original_str = " Where is my dog, john ? % your dog is on the table % really thanks john % you're welcome % Have a nice dog" keyword = "dog" # 拆分并清理短语 phrases = [phrase.strip() for phrase in original_str.split('%')] # 过滤匹配短语 matched_phrases = [phrase for phrase in phrases if keyword in phrase] # 拼接结果 result_str = ' // '.join(matched_phrases) print(result_str) # 输出:Where is my dog, john ? // your dog is on the table // Have a nice dog
额外优化:不区分大小写匹配
如果需要忽略大小写(比如要匹配"Dog"、"DOG"这类变体),只需要在过滤时统一转成小写判断即可:
- JavaScript:
phrase.toLowerCase().includes(keyword.toLowerCase()) - Python:
keyword.lower() in phrase.lower()
这个方案完全避开了复杂的索引定位逻辑,利用语言原生的字符串和数组方法就能高效完成需求,而且可读性超强,后续维护也方便~
内容的提问来源于stack exchange,提问作者Monick
相关产品推荐
相关产品推荐

