SnowyCoder
SnowyCoder

Reputation: 213

How can I find a digit after string with pattern?

I'm trying to get the last return code from an SSH shell in linux. I'm using the command:echo &? to get it. I've written following code but it's not working:

int last_len = 0;
Pattern p = Pattern.compile("echo $?\r\n[0-9]");
while(in.available() > 0 ) {
    last_len = in.read(buffer);
    String str = new String(buffer, 0, last_len);
    Matcher m = p.matcher(str);
    if(m.find()) {
        return Integer.parseInt(m.group().substring(9));
    }
}

What am I doing wrong?

Upvotes: 1

Views: 92

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to escape $, ? in the regex inorder to match the literal form of those characters since ?, $ are considered as special chars in regex.

Pattern p = Pattern.compile("echo \\$\\?\\r?\\n([0-9])");
Matcher m = p.matcher(str);
if(m.find()) {
System.out.println(m.group(1));
}

or

Pattern p = Pattern.compile("echo\\s+\\$\\?[\\r\\n]+([0-9])");

Upvotes: 1

Related Questions