regexjscript

How to match text string before and after a short hyphen with space


My heart will go on - Celine Dion
My heart will go on - Celine Dion
My heart will go on - Celine Dion
My heart will go on -Celine Dion
My heart will go on- Celine Dion
My heart will go on-Celine Dion

So that is my example String. each of the line must contain a short hyphen. And The space before or after short hyphen can be any number of space even some line have no space before or after short hyphen. I Need to match from every line 2 group of string. My heart will go on and Celine Dion. So Which Regular expression can do this?

/(.*)(\s\-\s)(.*)/gm this regular expression can match when there is a single space before and after the short hyphen ^(.*?)[\p{Zs}\t]+-[\p{Zs}\t]+(.*) This regular expression can match any number of space before and after short hyphen. But problem when there is no space maybe before and maybe after the short hyphen.


Solution

  • The following pattern seems to be working:

    (.*?)(?:\s*-\s*)(.*)
    

    This matches:

    Demo