let myString = "Hello 'How are you' foo bar abc 'Strings are cool' d b s ;12gh gh76;"

const myRegEx = / \w+ "\w* +" | ;\w +; +/g  // This what i have figured but its not working :(

const splitedString = myString.split(myRegEx)

console.log(splitedString)

Epected Output: ["Hello", "How are you", "foo", "bar", abc, "Strings are cool", "d", "b", "s", "12gh-gh76"]

让我试着解释更多:

首先,除'';;内的字符串外,所有字符串均以空格""为基础拆分,如: "Hello 'Yo what's up'"-->["Hello", "Yo-what's-up"](注意这里多了'个,所以也要处理这个.)

然后,如果字符串在;;内,则将其与-联系起来(我相信这是正确的名称),如下所示: Hello ;hi there;-->["Hello", "hi-there"]

并最终返回完成的所有格式化的array...不出所料.

推荐答案

您可以使用matchAll而不是Split来查找引号、分号对或使用正则表达式([';]).+?\1|\w+分隔的单词的匹配内容.

然后go 掉包装,并在需要的地方替换空格.

const myRegEx = new RegExp(/([';]).+?\1|\w+/gm)

const message = "Hello 'How are you' foo bar abc 'Strings are cool' d b s ;12gh gh76; ;a 'b c' d; 'a ;b c; d' d" // Try edit me

const matches = Array.from(message.matchAll(myRegEx))

const finalResult = matches.map(str => {
  const value = str.shift()
  if(value.match(/^;.*;$/))
    return value.substring(1, value.length-1).replaceAll(' ', '-')
  else if(value.match(/^'.*'$/))
    return value.substring(1, value.length-1)
  else
    return value
})

// Log to console
console.log(finalResult)

请注意,此解决方案基于包装器(引号和分号)不嵌套的假设而工作.

如果您需要考虑嵌套包装器,regex不是最好的工具,因为您将需要判断"括号"--平衡,而使用regex也是可能的,因为更容易做到这一点.

Javascript相关问答推荐

如何计算数组子级的深度- Vue.js

为什么在获取回调内设置状态(不会)会导致无限循环?

我无法在NightWatch.js测试中获取完整的Chrome浏览器控制台日志(log)

Vue:ref不会创建react 性属性

IMDB使用 puppeteer 加载更多按钮(nodejs)

将字符串UTC Date转换为ngx—counting leftTime配置值的数字

自定义高图中的x轴标签序列

我怎么才能得到Kotlin的密文?

rxjs插入延迟数据

更改预请求脚本中重用的JSON主体变量- Postman

如何使用JavaScript拆分带空格的单词

React.Development.js和未捕获的ReferenceError:未定义useState

当输入字段无效时,我的应用程序不会返回错误

连接到游戏的玩家不会在浏览器在线游戏中呈现

如何在Bootstrap中减少网格系统中单个div的宽度

在画布中调整边上反弹框的大小失败

未捕获的运行时错误:调度程序为空

将多个文本框中的输出合并到一个文本框中

如何在Jest中模拟函数

我无法在Api Reaction本机上发出GET请求