Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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_String_Split - Fatal编程技术网

Javascript 不明白为什么我的正则表达式不起作用?

Javascript 不明白为什么我的正则表达式不起作用?,javascript,regex,string,split,Javascript,Regex,String,Split,正在尝试创建一个正则表达式,该表达式在“,”和“\n”处拆分字符串,然后在代码中拆分传入的自定义分隔符,该分隔符由firstChar表示 正在传入的字符串的格式:{delimiter}\n{numbers}。我在网上使用过regex101,它似乎在那里工作,但在我的实际代码中,它没有在自定义分隔符处拆分,因此不确定我做错了什么 if (str.includes('\n')) { let firstChar = str.slice(0, 1); if (parseInt(first

正在尝试创建一个正则表达式,该表达式在“,”和“\n”处拆分字符串,然后在代码中拆分传入的自定义分隔符,该分隔符由firstChar表示

正在传入的字符串的格式:{delimiter}\n{numbers}。我在网上使用过regex101,它似乎在那里工作,但在我的实际代码中,它没有在自定义分隔符处拆分,因此不确定我做错了什么

if (str.includes('\n')) {
    let firstChar = str.slice(0, 1);
    if (parseInt(firstChar)) {
      strArr = str.split(/,|\n/) ;
    } else {
      strArr = str.split(/[,|\n|firstChar]/);
    }
}

期望'\n2;5'等于7,但由于某种原因,我的数组拆分为[;,2;5]。

您的第一个字符不是数字,因此直接转到else条件,如果您需要动态正则表达式,则需要使用正则表达式构建它

这里也不需要字符类

/[,|\n|firstChar]/
应该是

/,|\n|firstChar/
let splitter=str=>{ 如果str.包含“\n”{ 设firstChar=str.slice0,1; 如果parseIntfirstChar{ 返回str.split/,|\n/; }否则{ 让regex=newregexp`,\\\n \\${firstChar}`,'g'//在此处构建动态regex 返回str.splitregex.filterBoolean } } } 控制台。日志拆分器\n2;5.
console.logsplitter*\n2*5当我运行您的代码时,它会像这样拆分:[;,2;5],这不是我想要的。我想要[2,5]@JoeSpinelli你需要构建一个动态正则表达式,检查更新,我以前从未使用过动态正则表达式。我的案子让我需要它怎么办?为什么不这样传入:str.split/,|\n | firstChar/work?firstChar===';'那么,这不就是简单地传递“;”吗在表达式中?@JoeSpinelli firstChar将被视为单词firstChar,而不是变量firstChar,当你想要构建一个动态正则表达式时,你需要使用RegExpwowww来构建,真不敢相信我从来没有意识到smh哈哈,这太烦人了。非常感谢你,你太棒了!你的第一个字符不是一个数字,所以你最终会在每个语句中转到elsetime@CodeManiac这就是我想要的。如果第一个字符是一个数字,我想将其拆分为“\n”和“,”。否则,我希望在前面提到的分隔符以及传入的自定义分隔符“;”处拆分它在本例中,[\n | firstChar]与[\n,| Cafhirst]完全相同。