简体   繁体   中英

Regex delimit the start of a string and the end

I'm been having trouble with regex, which I doesn't understand at all.

I have a string '#anything#that#i#say' and want that the regex detect one word per #, so it will be [#anything, #that, #i, #say]. Need to work with spaces too :(

The closest that I came is [#\\w]+, but this only get 1 word and I want separated.

You're close; [#\\w] will match anything that is either a # or a word character. But what you want is to match a single # followed by any number of word characters, like this: #\\w+ without the brackets

 var str = "#anything#that#i#say"; var regexp = /#\\w+/gi; console.log(str.match(regexp)); 

It's possible to have this deal with spaces as well, but I'd need to see an example of what you mean to tell you how; there are lots of ways that "need to work with spaces" can be interpreted, and I'd rather not guess.

use expression >>  /#\s*(\w+)/g

\\s* : to check if zero or more spaces you have between # and word

This will match 4 word in your string '#anything#that#i#say' even your string is containing space between '#anything# that#i# say'

sample to check: http://www.regextester.com/?fam=97638

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