tags:

views:

336

answers:

4

I would like like to create a java regular expression that selects everything from file: to the last forward slash (/) in the file path. This is so I can replace it with a different path.

<!DOCTYPE "file:C:/Documentum/XML%20Applications/joesdev/goodnews/book.dtd"/>
<myBook>cool book</myBook>

Does anyone have any ideas? Thanks!!

A: 

"file:.*/[^/]*"/>

Martijn
Thanks... is it possible to not include anything beyond "goodnews/"
joe
You need to use ()s to group what you want and then get the appropriate group from the resulting match object.
Jeremy Huiskamp
+3  A: 

You just want to go to the last slash before the end-quote, right? If so:

file:[^"]+/

(the string "file:", then anything but ", ending with a /)
Properly escaped:

String regex = "file:[^\"]+/";
Michael Myers
This is what I came up with, but was too slow to post it before you.
dustyburwell
A: 

You could try to process this yourself, but a better scheme would be to just pick out the parts between the quotes and use java.util.File to separate the directory name from the filename. That way you don't have to worry about / vs \ or various escape characters.

Jeremy Huiskamp
A: 
String newPath = "C:/Documentum/badnews";
String originalPath = "<!DOCTYPE \"file:C:/Documentum/XML%20Applications/joesdev/goodnews/book.dtd\"/>";
System.out.println(originalPath.replaceFirst("file:C:((/[/\\w%]+))", newPath));
dfa