Search code examples
regexpathpcre

Surround input text with slash or backslash


I am trying to surround input string with either \ or /. The input string can only take one of the following forms. The first one is an empty string.


path
/path
\path
path/
path\
/path/
\path\

I am trying with ^[\\\/]?|[\\\/]?$. It works for the first four. The later four will have double slash or backslash with this regex. I know why this is happening but don't have any idea on how to fix it. I am using PCRE. I want the output to be / when the input is empty and /path/ for all others.

Current output:

/
/path/
/path/
/path/
/path//
/path//
/path//
/path//

regex101
I am only using the multiline flag for convenience.

EDIT: I have updated the solution by @the-fourth-bird to also replace / or \ that are in between.

Updated regex : ^[\\\/]?|[\\\/]+|(?<![\\\/])[\\\/]?$

EDIT 2: Even better by u/whereIsMyBroom over at reddit.

regex : ^[\\\/]?|[\\\/]|(?<![\\\/])$


Solution

  • You might write the pattern asserting not / or \ before the last slash using a negative lookbehind (?<![\\\/]

    ^[\\\/]?|(?<![\\\/])[\\\/]?$
    

    Regex demo