如何从字符串中提取连续字母单词并存入数组?
嘿,刚好我之前处理过类似的需求,给你整几个简单好用的实现方法,不管你用JS还是Python都能轻松搞定👇
JavaScript 实现方案
最直接的方式就是用正则表达式配合match()方法,一步到位得到单词数组。
拿你给出的示例字符串来说:
I want an array like this: This is what I currently have:
对应的代码如下:
const targetStr = "I want an array like this: This is what I currently have:"; // 匹配所有连续的大小写字母序列,返回数组 const wordsArray = targetStr.match(/[a-zA-Z]+/g); console.log(wordsArray); // 输出结果:["I", "want", "an", "array", "like", "this", "This", "is", "what", "I", "currently", "have"]
小解释:正则/[a-zA-Z]+/g里,[a-zA-Z]匹配单个大小写字母,+表示匹配连续的1个及以上,g是全局匹配模式,这样match()就会把所有符合条件的单词都捞出来放进数组里。
Python 实现方案
Python里用re模块的findall()方法同样能快速解决:
import re target_str = "I want an array like this: This is what I currently have:" # 提取所有连续字母序列组成数组 words_array = re.findall(r'[a-zA-Z]+', target_str) print(words_array) # 输出结果:['I', 'want', 'an', 'array', 'like', 'this', 'This', 'is', 'what', 'I', 'currently', 'have']
补充:如果你的字符串里包含带重音的非英语字母(比如法语的café、德语的Schön),可以把正则改成r'[^\W\d_]+',这样能匹配所有Unicode字母,适用性更广。
内容的提问来源于stack exchange,提问作者Silvestru




