简体   繁体   中英

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 .

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. 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.

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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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