简体   繁体   中英

Split string by whitespace, keeping escaped characters

I'm trying to split a string by its whitespace, but keep any escaped whitespace characters.

Example line:

/etc/space\ in\ folder\ name/files  /mnt/files  none    defaults    0   0

I want to split that up by the whitespace (tab or spaces) yet keep the escaped whitespace characters ( \ ) as one item.

So in this case it would split it into 6 items.

How can I achieve this?

A regular expression can match any escaped character, or any character that isn't a space:

 const str = String.raw`/etc/space\ in\ folder\ name/files /mnt/files none defaults 0 0`; console.log( str.match(/(?:\\.|\S)+/g) );

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