2

(textareaからの)テキストのブロックに@signが前に付いた単語が含まれているかどうかを検出しようとしています。

たとえば、次のテキストで:ねえ@ジョン、私はちょうど@スミスを見ました

@記号なしでそれぞれJohnとSmithを検出します。私はこのようなものがうまくいくと思いました:

@\w\w+

私の質問は、テキストが可変コメントに格納されていると仮定して、JavaScriptでテキストをフィルタリングするにはどうすればよいですか?

@記号なしで接頭辞@が付いたテキスト内の名前のみを出力する必要があります。

よろしく。

4

4 に答える 4

5

次のように、g(グローバル)フラグ、キャプチャグループ、およびループ呼び出しを使用しますRegExp#exec

var str = "Hi there @john, it's @mary, my email is mary@example.com.";
var re = /\B@(\w+)/g;
var m;

for (m = re.exec(str); m; m = re.exec(str)) {
    console.log("Found: " + m[1]);
}

出力:

見つかった:ジョン
見つかった:メアリー

実例| ソース


境界の推奨をしてくれた@AlexKに感謝します!

于 2012-06-12T16:00:55.230 に答える
1

comment.match(/@\w+/g)一致の配列(["@John", "@Smith"])が表示されます。

于 2012-06-12T15:59:26.900 に答える
1

興味がある場合に備えて、正規表現にチェックを追加して、メールアドレスと一致しないようにしました。

var comment = "Hey @John, I just saw @Smith."
        + " (john@example.com)";

// Parse tags using ye olde regex.
var tags = comment.match(/\B@\w+/g);

// If no tags were found, turn "null" into
// an empty array.
if (!tags) {
    tags = [];
}

// Remove leading space and "@" manually.
// Can't incorporate this into regex as
// lookbehind not always supported.
for (var i = 0; i < tags.length; i++) {
    tags[i] = tags[i].substr(1);
}
于 2012-06-12T16:27:40.707 に答える
0
var re = /@(\w+)/g; //set the g flag to match globally
var match;
while (match = re.exec(text)) {
    //match is an array representing how the regex matched the text.
    //match.index the position where it matches.
    //it returns null if there are no matches, ending the loop.
    //match[0] is the text matched by the entire regex, 
    //match[1] is the text between the first capturing group.
    //each set of matching parenthesis is a capturing group. 
}  
于 2012-06-12T16:00:31.527 に答える