如何编写正则模拟JS split功能 提取指定分隔符后的社区名称
解决方案
你的需求是提取固定分隔符-分割的最后一段内容作为社区名,用以下两种正则方案都可以实现:
方案1:通用兼容写法
正则表达式:/[^-]+$/
匹配逻辑为抓取字符串末尾所有非-的字符,匹配后去除首尾空格即可使用。
代码示例:
// 测试用例1 const test1 = "Iowa - Cedar Rapids - Meth-Wick Community"; const res1 = test1.match(/[^-]+$/)[0].trim(); console.log(res1); // 输出 Meth-Wick Community // 测试用例2 const test2 = "Iowa - Cedar Rapids - The Gardens of Cedar Rapids"; const res2 = test2.match(/[^-]+$/)[0].trim(); console.log(res2); // 输出 The Gardens of Cedar Rapids
方案2:精准匹配分隔符写法
如果需要严格匹配-这个完整分隔符,可以使用带后行断言的正则:/(?<= - )[^-]+$/
该正则会直接匹配最后一个-后面到字符串结尾的所有内容,不需要额外处理空格。
代码示例:
const str = "Iowa - Cedar Rapids - The Gardens of Cedar Rapids"; const community = str.match(/(?<= - )[^-]+$/)[0]; console.log(community); // 直接输出 The Gardens of Cedar Rapids
原代码错误原因
你之前使用的/([A-Z])\w{3}/gi正则的作用是匹配所有大写字母开头、后续跟3个单词字符的片段,和你要提取整段社区名称的需求完全不符,所以无法得到正确结果。
内容的提问来源于stack exchange,提问作者Code Guy
相关产品推荐
相关产品推荐

