简体   繁体   English

为什么这个 javascript regex split 函数不起作用?

[英]why isn't this javascript regex split function working?

I'm trying to split a string by either three or more pound signs or three or more spaces.我试图用三个或更多的磅符号或三个或更多的空格分割一个字符串。

I'm using a function that looks like this:我正在使用一个看起来像这样的函数:

     var produktDaten = dataMatch[0].replace(/\x03/g, '').trim().split('/[#\s]/{3,}');  
     console.log(produktDaten + ' is the data');

I need to clean the data up a bit, hence the replace and trim .我需要稍微清理一下数据,因此使用replacetrim

The output I'm getting looks like this:我得到的输出如下所示:

##########################################################################MA-KF6###Beckhoff###EL1808    BECK.EL1808###MA-KF7###Beckhoff###EL1808    BECK.EL1808###MA-KF12###Beckhoff###EL1808    BECK.EL1808###MA-KF13###Beckhoff###EL1808    BECK.EL1808###MA-KF14###Beckhoff###EL1808    BECK.EL1808###MA-KF15###Beckhoff###EL1808    BECK.EL1808###MA-KF16###Beckhoff###EL1808    BECK.EL1808###MA-KF19###Beckhoff###EL1808    BECK.EL1808 is the data

How is this possible?这怎么可能? Irrespective of the input, shouldn't the pound and multiple spaces be deleted by the split?无论输入如何,拆分不应该删除磅和多个空格吗?

You passed a string to the split , the input string does not contain that string.您将字符串传递给split ,输入字符串不包含该字符串。 I think you wanted to use我想你想用

/[#\s]{3,}/

like here:像这儿:

 var produktDaten = "##########################################################################MA-KF6###Beckhoff###EL1808 BECK.EL1808###MA-KF7###Beckhoff###EL1808 BECK.EL1808###MA-KF12###Beckhoff###EL1808 BECK.EL1808###MA-KF13###Beckhoff###EL1808 BECK.EL1808###MA-KF14###Beckhoff###EL1808 BECK.EL1808###MA-KF15###Beckhoff###EL1808 BECK.EL1808###MA-KF16###Beckhoff###EL1808 BECK.EL1808###MA-KF19###Beckhoff###EL1808 BECK.EL1808"; console.log(produktDaten.replace(/\\x03/g, '').trim().split(/[#\\s]{3,}/));

This /[#\\s]{3,}/ regex matches 3 or more chars that are either # or whitespace./[#\\s]{3,}/正则表达式匹配 3 个或更多字符,即#或空格。

NOTE: just removing ' around it won't fix the issue since you are using an unescaped / and quantify it.注意:只是删除它周围的'不会解决问题,因为您使用的是未转义的/并对其进行量化。 You actually need to quantify the character class, [#\\s] .您实际上需要量化字符类[#\\s]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM