Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法基于正则表达式拆分字符串_Javascript_Regex - Fatal编程技术网

Javascript 无法基于正则表达式拆分字符串

Javascript 无法基于正则表达式拆分字符串,javascript,regex,Javascript,Regex,我正在尝试使用正则表达式模式根据:之后的值拆分字符串 我希望结果是这样的 [ "hello", "js is fun!", "" ] 有人能帮忙吗 摘自我的代码 const str='0,0,5:hello0,1,5:js很有趣!0,2,0:' const result=str.match(/:[a-z]*/g); console.log(result)比@Nick的答案稍有改进,只是在字符类中包含空格: const

我正在尝试使用正则表达式模式根据
之后的值拆分字符串

我希望结果是这样的

[
  "hello",
  "js is fun!",
  ""
]
有人能帮忙吗

摘自我的代码

const str='0,0,5:hello0,1,5:js很有趣!0,2,0:'
const result=str.match(/:[a-z]*/g);

console.log(result)
比@Nick的答案稍有改进,只是在字符类中包含空格:

const str='0,0,5:hello0,1,5:js很有趣!0,2,0:'

const result=str.match(/(?要实现您从输入中描述的结果,您应该针对此正则表达式:

(?<=:)\D*

您尝试的模式不匹配,因为字符类不包含空格,
将是匹配的一部分。您可以使用
:([a-z\s]*)
将其转换为捕获组

另一个选项是使用捕获组,使用匹配组1中的
和捕获可选非数字
(\D*)

const str=“0,0,5:hello0,1,5:js很有趣!0,2,0:”; 让result=Array.from(str.matchAll(/:(\D*)/g),m=>m[1]); console.log(结果);
使用

const str='0,0,5:hello0,1,5:js很有趣!0,2,0:1,0,2:22';
常数rx=/(\d+(?:,\d+{2}):([^::*?)(?=\d+(?:,\d+{2}:$)/g;

console.log(Array.from(str.matchAll(rx),x=>[x[1],x[2]]);
太好了!有没有办法使用该正则表达式创建一对?
[0,0,5,“hello”]
。我尝试使用
split
,但似乎不起作用。@scriobh请查看我的编辑,您可以使用
字符串进行编辑。matchAll
非常快速!如何包含此字符串中的数字
'0,0,5:hello0,1,5:js很有趣!0,2,0:1,0,2:22'
@scriobh不太快-相当复杂!这可能会满足您的要求。
const result=[…str.matchAll(/(\d+,\d+,\d+):(.*(?=\d+,\d+,\d+,\d+)/g)].map(a=>a.slice(1))
是的。:(看起来最后一个给出的是
[“110,2,2”,“22”]
,应该是
[“1,0,2”,“22”]
。如何通过不排除这些正则表达式来包含数字,
/:()/g
该模式似乎不适用于此字符串:(
'0,0,5:hello0,1,5:js很有趣!0,2,0:1,0,2:22'
@scriobh您希望得到什么结果?哇!太好了。该模式确实有效。