简体   繁体   中英

RegExp capturing in Javascript

I have a string like this:

#ud %+^'()=%^'K%J+^K$#££½6 u896%+& 547900

I want to capture this #ud in a first variable and anything else that comes after, in a second variable, but not including the first space.

PS: #ud can change to #u64 , #d and etc.

How do I do it in a clean and simple way?

Try

/^(#[^ ]+) (.+)$/

I use the space character to find the end of the first part.

https://www.debuggex.com/r/VZcx0JLtfY4vNrzR

You can use a regex to split the string:

 var re = /^(\\S+)\\s(.*)/; var str = '#ud %+^\\'()=%^\\'K%J+^K$#££½6 u896%+& 547900'; alert(str.split(re).filter(Boolean)); 

The /(\\S+)\\s(.*)/ regex will match first characters that are not spaces with (\\S+) and capture it, then the space, and then it captures the rest of the string. Capturing groups are necessary to add the texts to the resulting array. And the .filter(Boolean) function removes empty items from the array.

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