1

I'm having trouble with a regex solution where I believe my solution is correct, but the matching is not as I would expect.

Can someone please help me understand where my thinking is going wrong?

Here is the problem I am solving, my regex, and what is going wrong:

Problem To Solve

I am given a series of strings representing folders, for example:

"TopLevelFolder"
"TopLevelFolder\Parent"
"TopLevelFolder\Parent\Child"

I am aiming to convert these into the following strings for displaying in a select list:

"TopLevelFolder"
"...\Parent"
"...\...\Child"

My Regex

Engine: Dot Net

Language: C#

(([^\\]+\\)+)

regex101 example:

https://regex101.com/r/zY1oM5/1

This regex is trying to: One or more times, find one or more characters that aren't a backslash, and then a backslash, and put that match in a capture group.

For example, in "TopLevel\Parent\Child", put each of "TopLevel\" and "Parent\" in a capture group.

What's Going Wrong

The returned capture groups for this regex in this example include:

"TopLevel\Parent\"
"Parent\"

I believe the first group should not be being captured, because I asked that the characters before the final backslash not include a backslash.

Clearly, my expectations and understanding are wrong. What should I be doing here, and how is my understanding wrong?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Jamie Butler
  • 235
  • 1
  • 2
  • 19

1 Answers1

1

It seems like you want a lazy match. Remove the outer capturing group and then add the ? quantifier at the end of the expression so that + is no longer greedy. This will allow each substring to be captured as expected.

/([^\\]+\\)+?/g

An input of TopLevel\Parent\Child will return:

TopLevel\
Parent\

Updated Example


Then you can replace /([^\\]+\\)+?/g with ..\\.

An input of TopLevelFolder\Parent\Child would output: ..\..\Child.

And likewise, TopLevelFolder\Parent would output ..\Parent.

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Fantastic, thanks very much! It turns out I was also missing the necessary global modifier that you added. Much appreciated :) – Jamie Butler Jan 04 '16 at 05:05