user2971238
user2971238

Reputation: 85

regular expression to get the name of java file

I hava a code like this

theResult.setFile(fileNode.getText().toUpperCase());

that gives me an output a path of a file in my drive like this.

D:\workspace\try\myFile.java

How can regex just give me the name of my file ? So, in output just show

myFile.java

Thanks...

Upvotes: 0

Views: 69

Answers (2)

Unihedron
Unihedron

Reputation: 11041

Use the following regex:

/^.*\\(.*?.java)$/

The code would become:

theResult.setFile(fileNode.getText().toUpperCase()).replaceFirst("^.*\\\\(.*?.java)$", "$1");

Regex parsers reads lines based on modifiers very sensitively. On .* this matches the entire line, where it sees \\ (literal \) it backtracks to the last backslash in line, so everything after that is our file name when and only when it matches "something.java". .*? is a non-greedy match, meaning instead of eating the whole word it reads character by character until it hits .java. It is captured in a capture group ( ) and we retrieve it with $1 (Capture group 1).

View a regex demo.

Upvotes: 1

Nile
Nile

Reputation: 396

String text = "D:\\workspace\\try\\myFile.java";
String name = text.substring(text.lastIndexOf("\\")+1);

Upvotes: 1

Related Questions