【问题标题】:Javascript : Extract words starting with specific character in a stringJavascript:提取字符串中以特定字符开头的单词
【发布时间】:2015-04-28 15:43:57
【问题描述】:

我有这个字符串:

Hey I love #apple and #orange and also #banana

我想提取以# 符号开头的每个单词。

目前我正在用这段代码实现它:

var last = 0;
var n = 0;
var str = "Hey I love #apple and #orange and also #banana";
do{
    n = str.indexOf("#", last);
    if(n != -1){
        //The code found the # char at position 'n'
        last = n+1; //saving the last found position for next loop

        //I'm using this to find the end of the word
        var suffixArr = [' ', '#'];
        var e = -1;
        for(var i = 0; i < suffixArr.length;i++){
            if(str.indexOf(suffixArr[i], n) != -1){
               e = str.indexOf(suffixArr[i], n+1);
               break;
            }
        }
        if(e == -1){
            //Here it could no find banana because there isn't any white space or # after
            e = str.length; //this is the only possibility i've found
        }

        //extracting the word from the string
        var word = str.substr(n+1, (e-1)-n);
   }
}
while (n != -1);

我怎样才能找到仅以# 和a-Z characters 开头的单词。例如,如果我有#apple!,我应该能够提取apple 而且,正如我在代码中提到的,如果单词出现在字符串的末尾,我如何设法获取它

【问题讨论】:

标签: javascript regex string


【解决方案1】:
(?:^|[ ])#([a-zA-Z]+)

试试这个。抓住捕获。查看演示。

https://regex101.com/r/wU7sQ0/18

    var re = /(?:^|[ ])#([a-zA-Z]+)/gm;
var str = 'Hey I love #apple and #orange and #apple!@ also #banana';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

【讨论】:

  • 您可以轻松地将“#”替换为空白值并获取剩余的字符串。 VKS 的解决方案将起作用。
  • 非常感谢!到时候我真的需要学习正则表达式..:)
  • @vks:我想知道为什么要添加^|,因为我们也可以使用?:[ ] 获得空间谢谢
  • @ρяσѕρєяK 如果单词在句首,后面不会有空格。为此我添加了^|
  • @vks 如果有人写#orange#apple,我怎么能得到。您的代码目前仅显示 orange。我尝试删除正则表达式中的(?:^|[ ]),但想确定
【解决方案2】:

您可以使用正则表达式/(^|\s)#[a-z]+/imatch,然后使用Array.join(这里在执行+ ""时在内部使用)并从形成的字符串中替换所有#并拆分在,

var arr = (str.match(/(^|\s)#[a-z]+/i)+"").replace(/#/g,"").split(",");

如果您还想在Some#test 中匹配test,请从正则表达式中删除(^|\s)

【讨论】:

    最近更新 更多