-4

In the following example string:

$cd = "..\folder\file.xml"

to match everything after the last slash I use:

[^\\]+$

or to match everything from a sequence of characters and ignore the final quote:

(file\.[^"]*)

How would I combine these to match everything from the last slash to the end of the line ignoring the final quote?

Arno
  • 307
  • 1
  • 4
  • 14

2 Answers2

1

The regular expression

([^\/]+). 

will solve this problem for you.

'[^/]' means capture all characters except for / (the backslash is to escape the / character, in some cases you might not need to escape it)

'+' means one or more of the previous (previous = [^/])

'.' means match any character except newline

the parentheses around everything but the '.' will make sure that you capture everything before the slash but not the character that follows it (in your case the trailing quote).

If you are having trouble with regular expressions, https://regex101.com/ is a very good website to help you with it. The website also provides real time information on what you are actually doing/trying with your regular expression.

Julian Declercq
  • 1,536
  • 3
  • 17
  • 32
1

You can use this:

([^\/]+)(?="$)

It will match anything after the last slash up to a quotation mark at the end of the line "$ (without including it in the match).

Demo: https://regex101.com/r/mY9nI1/1

Maria Ivanova
  • 1,146
  • 10
  • 19
  • awesome, just changed it to `code ([^\\]+)(?="$)` for the backslash, my bad for not having the example there, add the example – Arno Jul 20 '16 at 10:49
  • any idea why this works with python 2.7.11 in Windows and not with python 2.7.5 in Linux? – Arno Aug 02 '16 at 09:46
  • Perhaps you can try this one: https://regex101.com/r/jJ6hH0/1 I am not sure why it doesn't work in python 2.7.5 in Linux, perhaps it doesn't support lookaheads? If this is the case, the pattern in the link should work. – Maria Ivanova Aug 02 '16 at 10:23
  • 1
    Much appreciated Maria, it turned out to be the windows newline character, when I do an rstrip() on the line before the regex the problem goes away. – Arno Aug 03 '16 at 08:19