Regex JavaScript capture till (before) optional string

I've a regex

(\/)?([\s\S]+)(?:@bigletterbot)?

When I match : /random@bigletterbot

Expected Output:

["/random@bigletterbot","/","random"]

However it is giving

["/random@bigletterbot","/","random@bigletterbot"]

Moreover when I match

Hello World!

it is giving desired output. I tested at regex101.

Please tell me what I'm doing wrong.

Requirements:

/ is optional and if present should be captured, [\s\S]+ is meant to be captured: which can be: Hello World or Hello @ WorldI thinks @ is making it difficult otherwise[^@]+should work and third part is a optional string @bigletterbot which should not be captured

Answers


The regex you may use to match and capture an optional / followed with any characters but a @ or @ symbols that are not followed with a word character is

(\/)?([^@]*(?:@\B[^@]*)*)

See the regex demo

The part I add is [^@]*(?:@\B[^@]*)*:

  • [^@]* - 0+ characters other than @
  • (?:@\B[^@]*)* - 0+ sequences of:
    • @\B - @ that is not followed with a word character (as \B is a non-word boundary)
    • [^@]* - 0+ characters other than @

When a substring is not to be "matched" (you say @something should not be captured, but actually mean it should not be matched), it means you need to match up to that substring. Thus, a negated character class solution is the best here, but it is complicated a little because you want to allow @ + non-word characters combinations. The \B should cope with those situations as user names should conform to the @\w+ pattern (so, all the @mentions will be safely stopped from matching with @\B).


Well, try following regex:

/((\/?)([^@]+).*)/g

Based on your sample input, output will be:

1.  `/random@bigletterbot`
2.  `/`
3.  `random`

Try demo


Need Your Help

How I receive this ajax param in Cakephp?

jquery ajax cakephp cakephp-2.0 jquery-select2

I have a select2 plugin with ajax: http://ivaynberg.github.io/select2/