JavaScript regexp selects only the last occurrence

Select only the last occurrence

I try to select the last word (before the space), they appear after the last character white spaceand @.

Below is my line

hello hi @why helo @blow but @name             // capture: name
hello hi @why helo @blow but name@name         // capture: blow

and one more line

@blow but not know how to resolve this         // capture: blow

Here the last occurrence is the first word blow, select only @after the word (obviously, the space is not in the first word).

I tried this: https://regex101.com/r/pG1kU1/1

+4
source share
5 answers

The simplest answer:

/\B@[^@]\w*(?!.*?\s@)/

See DEMO

+2
source

You can simply use a negative scan:

@[^@]\w*(?!.*@[^@]\w*)

regex101 demo .

(?:) , . , @-. , @ - .

, :

@blow but not know how to resolve this@
^                                     ^
|                                     |
will match this one                   |
        because this is not a valid @/

@blow, @ - . @, :

@[^@]?\w*(?!.*@[^@]?\w*)

@[^@]?\w*(?!.*@)

@ , \B:

\B@[^@]?\w*(?!.*\B@[^@]?\w*)

regex101 demo

+1
/(?:^|\s)(@[^@]\w*)(?!.*\s@)/

; . , lookbehinds,

/(?<=^|\s)@[^@]\w*(?!.*\s@)/

, ; JavaScript.

, :

/\b@[^@]\w*(?!.*\s@)/

The idea is to check with a positive look that after our coincidence there will be no @word.

+1
source
(?:^| )@([^@\s]+)(?!.*?\s@\w+.*$)

You can try this. Watch the demo.

https://regex101.com/r/pG1kU1/3

0
source

As an alternative, how about something like that?

var strings = [
    'hello hi @why helo @blow but @name',
    'hello hi @why helo @blow but name@name',
    '  hello   hi   @why   helo    @blow    but    name@name  ',
    '@blow but not know how to resolve this',
    '  @blow   but   not   know   how   to   resolve   this',
    'tada',
    '    ',
    ''
];

var wanted = strings.map(function (element) {
    var found = 'not found';
    
    element.split(/\s+/).reverse().some(function (part) {
        if (part.charAt(0) === '@') {
            found = part.slice(1);
            
            return true;
        }
    });
    
    return found;
});

document.getElementById('out').textContent = wanted.join('\n')
<pre id='out'></pre>
Run codeHide result

No complicated RegExp, easy to understand and change behavior. requires ES5 or gaskets, but not big.

0
source

All Articles