简体   繁体   English

正则表达式分隔字符串的开头和结尾

[英]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]. 我有一个字符串'#anything#that#i#say',并希望正则表达式每#检测一个单词,所以它将是[#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. 我最接近的是[#\\ w] +,但这只有1个字,我想分开。

You're close; 你近了 [#\\w] will match anything that is either a # or a word character. [#\\w]将匹配任何#或单词字符。 But what you want is to match a single # followed by any number of word characters, like this: #\\w+ without the brackets 但是您想要的是匹配一个#后跟任意数量的单词字符,例如: #\\w+不带括号

 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 \\ s *:检查#和单词之间是否有零个或多个空格

This will match 4 word in your string '#anything#that#i#say' even your string is containing space between '#anything# that#i# say' 这将匹配您的字符串'#anything#that#i#say'中的4个单词,即使您的字符串中包含'#anything#that#i#say'之间的空格

sample to check: http://www.regextester.com/?fam=97638 检查样本: http : //www.regextester.com/?fam=97638

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

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