user2614607
user2614607

Reputation: 151

Regular expression for string between escape characters

I have a string and I want to extract substring between escape characters.

e.g.

   AC001 (\\Test123\homedir$) (H:)

How can i get Test123 in java

Upvotes: 1

Views: 173

Answers (4)

Bohemian
Bohemian

Reputation: 425448

In one line:

String middle = str.replaceAll(".*\\\\(.*?)\\h.*", "$1");

This regex matches the entire string, but captures the target, which is the returned using a back reference.

Upvotes: 0

anubhava
anubhava

Reputation: 786359

Without regex you can do:

String str = "AC001 (\\\\Test123\\homedir$) (H:)"; 
String substr = str.substring(str.indexOf('\\')+2, str.indexOf('\\', str.indexOf('\\')+2));
//=> Test123

Upvotes: 0

sr01853
sr01853

Reputation: 6121

String s = "AC001 (\\Test123\homedir$) (H:)";

s = s.substring(s.indexOf('\\') + 2);
s = s.substring(0, s.indexOf('\\'));

System.out.println(s);

Upvotes: 0

Masudul
Masudul

Reputation: 21981

Try,

    String input = "AC001 (\\Test123\\homedir$) (H:)";
    String regex="(\\\\.*\\\\)";
    Pattern ptrn = Pattern.compile(regex);
    Matcher mtchr = ptrn.matcher(input);
    while (mtchr.find()) {
        String res=mtchr.group();
        System.out.println(res.substring(1, res.length()-1));
    }

Upvotes: 1

Related Questions