如何用兼容Safari的正则分割含数字+空格的字符串
按「数字+空格」分割字符串(兼容Safari)
问题背景
待处理字符串:
1 The dog is big 2 The dog is sitting on the sofa 3 The dog was born on the 4th of July 4 The dog is named Henry
需要按「数字+空格」的位置分割成数组,每个元素包含对应数字及后续内容,直到下一个「数字+空格」出现。但之前用正则\s*\d+\D+会错误分割4th这类句子中间的数字,得到错误结果:
["1 The dog is big","2 The dog is sitting on the sofa","3 The dog was born on the","4th of July","4 The dog is named Henry"]
期望正确结果:
["1 The dog is big","2 The dog is sitting on the sofa","3 The dog was born on the 4th of July","4 The dog is named Henry"]
要求实现时不能使用前瞻断言(Safari不支持)。
解决方法
用「替换+分割」的组合方式实现,完全兼容Safari:
步骤说明
- 用正则
(\s)(\d+ )匹配所有作为分隔符的「空格+数字+空格」,把它替换成|$2——用|替代前面的空格,保留「数字+空格」部分。 - 对处理后的字符串用
split('|')分割,就能得到目标数组。
示例代码(JavaScript)
const originalStr = "1 The dog is big 2 The dog is sitting on the sofa 3 The dog was born on the 4th of July 4 The dog is named Henry"; // 替换分隔位置 const processedStr = originalStr.replace(/(\s)(\d+ )/g, "|$2"); // 分割得到结果 const resultArray = processedStr.split('|'); console.log(resultArray);
输出结果
["1 The dog is big","2 The dog is sitting on the sofa","3 The dog was born on the 4th of July","4 The dog is named Henry"]
原理说明
- 正则
(\s)(\d+ )只匹配前面是空格、后面跟着空格的数字,不会匹配4th这种数字后直接跟字母的情况,从根源避免错误分割。 - 替换操作把分隔位置的空格换成特殊符号
|,同时保留了每个区块开头的「数字+空格」,确保分割后的每个元素都是完整的目标内容。 - 全程未使用前瞻断言,完美适配Safari环境。
内容的提问来源于stack exchange,提问作者Niwa
相关产品推荐
相关产品推荐

