Home > Blockchain >  Regex between last two characters
Regex between last two characters

Time:10-02

I have a querstion about simple regex. I need to get between of these characters: - and ~

My string: Champions tour - To Win1 - To Win2 ~JIM FURYK

When I use this: \-([^)] \~) it is giving as matched this:

To Win1 - To Win2 ~

But I need this:

To Win2 ~JIM FURYK

Is it possible to this?

My regex is here: https://regex101.com/r/fJBLXb/1/

CodePudding user response:

You could use match as follows:

var input = "Champions tour - To Win1 - To Win2 ~JIM FURYK";
var output = input.match(/- ([^-] ~.*)$/)[1];
console.log(output);

The regex pattern used above says to match:

-          a hyphen
[ ]        a single space
(          capture what follows
    [^-]   match all content WITHOUT crossing another hyphen
    ~      ~
    .*     all remaining content
)          stop capture
$          end of the string

CodePudding user response:

Just add \-([^-)] \~) - dash to not match

CodePudding user response:

Your \-([^)] \~) regex matches the leftmost - that is directly followed with one or more chars other than ) (so it matches -, a, §, etc.) and then a ~ char. It does not stop at - chars and thus can match any amount of hyphens.

To match the value after last hyphen you can use

[^\s-][^-]*$

See the regex demo and the regex graph. Details:

  • [^\s-] - a char other than whitespace and -
  • [^-]* - zero or more chars other than -
  • $ - end of string.

See the JavaScript demo:

const text = 'Champions tour - To Win1 - To Win2 ~JIM FURYK';
const match = text.match(/[^\s-][^-]*$/);
if (match) {
    console.log(match[0]);
}

  • Related