10

私は正規表現が初めてです。改行を含まない文字列で「#」で始まる単語と一致させようとしています (コンテンツは既に改行で分割されています)。

例 (動作しない):

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' ]

少なくとも 1 つの文字、数字、または記号が続く限り、「#」の任意のインスタンスに一致させ、その直後のものを取得しようとしています。スペースまたは改行で一致を終了する必要があります。'#' は、文字列を開始するか、スペースで先行する必要があります。

この PHP ソリューションは良さそうに見えますが、JS 正規表現が持っているかどうかはわかりません: regexp keep/match any word that starts with a specific character.

4

3 に答える 3

14
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);

于 2012-11-25T18:51:14.023 に答える
4

Try this:

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);

于 2012-11-25T18:50:27.900 に答える
1

実際にはハッシュも一致させる必要があります。現在、単語の文字ではないいくつかの文字の 1 つがすぐ後に続く位置に続く単語の文字を探しています。明らかな理由で、これは失敗します。代わりにこれを試してください:

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

もちろん、先読みは今では冗長なので、削除することもできます:

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

これは望ましいものを返します:[ 'iPhone', 'delete' ]

ここにデモンストレーションがあります: http://jsfiddle.net/w3cCU/1/

于 2012-11-25T18:49:32.223 に答える