Monica
Monica

Reputation: 1534

How can I get the last word after a special character?

So far I have the following:

 \- (.*)

And from the following text:

September 2014 - Media

I need to get "Media", tho I am getting "- Media"

Upvotes: 0

Views: 114

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

Your regex is correct just print the group index 1 instead of group 0 and you don't need to escape - symbol.

DEMO

See the captured string Media at the right side in the above demo link.

OR

Use the below regex to match only Media,

- \K.*

DEMO

You could use a lookbehind if your language fail to support \K,

(?<=- ).*

DEMO

> "September 2014 - Media".match(/[^- ]+$/g)
[ 'Media' ]
> var r = "September 2014 - Media";
undefined
> console.log(/- (.*)/.exec(r)[1])
Media

Upvotes: 2

blackSmith
blackSmith

Reputation: 3154

If your language allows lookbehind, try :

  (?<=-)(.*) 

if doesn't simply use :

  ([^-]*)$

Upvotes: 2

Related Questions