简体   繁体   中英

Regular Expression starts with @ symbol

In regular expression, how do I look for matches that start with an @symbol? The symbol cannot be in the middle of a word (link in an email address).

For example, a string that looks like this:

@someone's email is blah@gmail.com and @someoneelse wants to send an email.

The expression I'd use is /^@[\w]/g

It should return:

@someone's

@someoneelse

The expression I use doesn't seem to work.

You can utilize \\B which is a non-word boundary and is the negated version of \\b .

var s = "@someone's email is blah@gmail.com and @someoneelse wants to send an email.",
    r = s.match(/\B@\S+/g);

console.log(r); //=> [ '@someone\'s', '@someoneelse' ]

You can use lodash , if you are using JavaScript.

words function from javascript takes two params. first param is for sentence and the second one is optional. You can pass regex which will find the word with starting letter " @ ".

import _ from "lodash";

_.words(sentence, /\B@\S+/g);
/(^|\s)@\w+/g

The [\\w] only matches a single word character, so thats why your regex only returns @s . \\w+ will match 1 or more word characters.

If you want to get words at the beginning of the line or inside the string, you can use the capture group (^|\\s) which does either the beginning of the string or a word after a whitespace character.

DEMO

var str="@someone's email is blah@gmail.com and @someoneelse wants to send an email.";
console.log(str.match(/(^|\s)@\w+/g)); //["@someone", " @someoneelse"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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