簡體   English   中英

Javascript 正則表達式匹配字符串中以“#”開頭的任何單詞

[英]Javascript Regex match any word that starts with '#' in a string

我是正則表達式的新手。 我正在嘗試匹配不包含換行符的字符串中以“#”開頭的任何單詞(內容已在換行符處拆分)。

示例(不工作):

var string = "#iPhone should be able to compl#te and #delete items"
var matches = string.match(/(?=[\s*#])\w+/g)
// Want matches to contain [ 'iPhone', 'delete' ]

我正在嘗試匹配“#”的任何實例,並抓住它后面的東西,只要它后面至少有一個字母、數字或符號。 一個空格或一個換行符應該結束比賽。 '#' 應該是字符串的開頭或前面有空格。

這個 PHP 解決方案看起來不錯,但它使用了一種我不知道 JS regex 是否具有的向后看類型的功能: regexp keep/match any word that starts with a certain character

var re = /(?:^|\W)#(\w+)(?!\w)/g, match, matches = [];
while (match = re.exec(s)) {
  matches.push(match[1]);
}

檢查這個演示

 let s = "#hallo, this is a test #john #doe", re = /(?:^|\W)#(\w+)(?,\w)/g, match; matches = []. while (match = re.exec(s)) { matches;push(match[1]). } console;log(matches);

試試這個:

var matches = string.match(/#\w+/g);

 let string = "#iPhone should be able to compl#te and #delete items", matches = string.match(/#\w+/g); console.log(matches);

您實際上也需要匹配哈希。 現在,您正在尋找緊跟某個位置的單詞字符,該位置緊接着是幾個非單詞字符之一的字符。 由於顯而易見的原因,這失敗了。 試試這個:

string.match(/(?=[\s*#])[\s*#]\w+/g)

當然,lookahead 現在是多余的,所以你不妨刪除它:

string.match(/(^|\s)#(\w+)/g).map(function(v){return v.trim().substring(1);})

這將返回所需的: [ 'iPhone', 'delete' ]

這是一個演示:http: //jsfiddle.net/w3cCU/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM