I’m looking for data that looks like abc/def. There may be whitespace around the text anywhere, so all of the following would be valid: abc__/_def or __abc/__def__. (Using underscores to visualize spaces.)
I came up with this regular expression:
(?<=\s*)abc\s*\/\s*def(?=\s*|^)
This works to find matches. I only recently picked up look-ahead and tried this expression to exclude spaces around / from the match (so abc__/_def would produce a match abc/def):
(?<=\s*)abc(?=\s*)\/(?=\s*)def(?=\s*|^)
This expression doesn’t work – I obviously misunderstand something about look-aheads. Can someone explain the difference between the two expressions? (Is it even possible what I’m trying to do? After reading the Regex documentation I thought it was but maybe I’m wrong.)
The match returned by any .NET regex is a contiguous substring of the original string. This means that you cannot get rid of the space around the “/” character. You can get rid of the outer spaces though.
A good approach would be to match
abcanddefusing named groups and extract that information usingTry this:
^\s*(?<part1>\w+)\s*/\s*(?<part2>\w+)\s*$Oftentimes the regex is more natural with named groups and without lookaround.