0

Content of file display.props, loaded via .xml

Xvfb Display Properties
Wed Jul 27 18:31:50 CEST 2016
DISPLAY=\:20
XAUTHORITY=/tmp/Xvfb4443942380574278711.Xauthority

Now I want to read this file and get the disply number (20)

    String xvfbPropsFile = System.getProperty("display.props");
    Pattern p = Pattern.compile("DISPLAY.*([0-9][0-9])",
            Pattern.MULTILINE|Pattern.DOTALL);
    Matcher m=p.matcher(xvfbPropsFile);

However this match and all the others that I tried do not work, any ideas?

  • The display number can be one digit, and `.*` is greedy. Try `DISPLAY.*?(\d+)` to make the `.*` stop as soon as a digit is encountered. – Jim Garrison Jul 27 '16 at 16:39
  • Remove `Pattern.MULTILINE|Pattern.DOTALL` – anubhava Jul 27 '16 at 16:40
  • The description *do not work* is not appropriate. You should have mentioned you get the last 2 digits in the string. You actually need to get the first two digits after DISPLAY. All you need is `"DISPLAY.*?([0-9][0-9])"`. The MULTILINE modifier is redundant. – Wiktor Stribiżew Jul 27 '16 at 18:32

2 Answers2

0

Try regex with String#replaceALl() ==> replaceAll("(?s).*DISPLAY=.*?(\\d+).*", "$1")

System.out.println(s.replaceAll("(?s).*DISPLAY=.*?(\\d+).*", "$1"));

O/P :

20
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

There are 2 problems on your code, first one you are using a greedy operator with flag DOTALL, so you will match a different string than you want (11 instead 20). You can solve this by using an ungreedy operator .*? or just remove the DOTALL flag.

Additionally the 2nd problem is that you have to grab the captured content from capturing groups with m.group(1):

String xvfbPropsFile = "Xvfb Display Properties\n" +
                            "Wed Jul 27 18:31:50 CEST 2016\n" +
                            "DISPLAY=\\:20\n" +
                            "XAUTHORITY=/tmp/Xvfb4443942380574278711.Xauthority";
Pattern p = Pattern.compile("DISPLAY.*([0-9][0-9])");
Matcher m=p.matcher(xvfbPropsFile);

if (m.find()){
    System.out.println(m.group(1)); // group 1 contains 20
}

IdeOne demo

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123