如何使用自定义正则表达式按规则分割JavaScript字符串?
字符串分割与格式化解决方案
问题代码
let myString = "Hello 'How are you' foo bar abc 'Strings are cool' d b s ;12gh gh76;" const myRegEx = / \w+ "\w* +" | ;\w +; +/g // 这是我写的正则,但无法正常工作:( const splitedString = myString.split(myRegEx) console.log(splitedString)
需求说明
- 整体按空格分割字符串,但单引号
''或双分号;;包裹的内容作为整体,不按空格分割 - 单引号内的内容保留原有单引号(如
'Yo what's up'需转为'Yo-what's-up') - 双分号内的内容将空格替换为连字符
-(如';hi there;'需转为'hi-there') - 最终返回经过格式化处理后的数组
预期输出
["Hello", "How are you", "foo", "bar", "abc", "Strings are cool", "d", "b", "s", "12gh-gh76"]
解决方案
你的正则无法工作是因为没有正确匹配单引号/分号包裹的内容,且用split处理这类带例外规则的分割场景并不合适,更高效的方式是直接匹配所有需要保留的片段,再分别处理:
方案1:完全匹配预期输出
如果需要单引号内保留空格、仅分号内替换空格为连字符,使用以下代码:
let myString = "Hello 'How are you' foo bar abc 'Strings are cool' d b s ;12gh gh76;" // 匹配三类内容:单引号包裹的、分号包裹的、普通非空格单词 const matchRegex = /'([^']+)'|;([^;]+);|(\S+)/g; const result = []; myString.replace(matchRegex, (_, quoted, semicoloned, plain) => { if (quoted) { // 单引号内容:去掉外层引号,保留内部空格和单引号 result.push(quoted); } else if (semicoloned) { // 分号内容:去掉外层分号,空格替换为连字符 result.push(semicoloned.replace(/\s+/g, '-')); } else if (plain) { result.push(plain); } }); console.log(result); // 输出:["Hello", "How are you", "foo", "bar", "abc", "Strings are cool", "d", "b", "s", "12gh-gh76"]
方案2:完全匹配需求描述
如果需要实现单引号内空格也替换为连字符(如'Yo what's up'转为'Yo-what's-up'),只需修改单引号内容的处理逻辑:
// ... 正则部分同上 if (quoted) { // 单引号内容:去掉外层引号,空格转连字符,保留内部单引号 result.push(quoted.replace(/\s+/g, '-')); } // ... 其余逻辑不变 // 输出:["Hello", "How-are-you", "foo", "bar", "abc", "Strings-are-cool", "d", "b", "s", "12gh-gh76"]
正则说明
'([^']+)':匹配单引号包裹的内容,捕获引号内的所有字符(不含外层引号);([^;]+);:匹配分号包裹的内容,捕获分号内的所有字符(不含外层分号)(\S+):匹配连续的非空格字符,即普通单词/g:全局匹配所有符合规则的片段
内容的提问来源于stack exchange,提问作者user20681417
相关产品推荐
相关产品推荐

