hell_storm2004
hell_storm2004

Reputation: 1605

Cant Find REGEX match for Multiline String

I am trying to make regular expression to search a string for a multi-line pattern. An example of the string is:

!
map-class frame-relay TempMap_1
 frame-relay cir 1536000
 frame-relay bc 15360
 frame-relay mincir 281000
 frame-relay adaptive-shaping becn
 service-policy output AB_TEMP_F1536K_0-256K-384K-128K_18
logging trap debugging
logging source-interface Loopback1
logging 136.91.111.21

The matching string i am trying to extract is

map-class frame-relay TempMap_1
 frame-relay cir 1536000
 frame-relay bc 15360
 frame-relay mincir 281000
 frame-relay adaptive-shaping becn
 service-policy output AB_TEMP_F1536K_0-256K-384K-128K_18

The pattern i have

map-class frame-relay TempMap_1[]*

Pattern pattern = Pattern.compile("map-class frame-relay TempMap_1[]*", Pattern.DOTALL);

I am not quite sure to put within [] to make the regular expression work. I am using Java and Pattern.DOTALL to match string. Any help would be appreciated.

Upvotes: 1

Views: 140

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626825

With Java 8, you may leverage the indentation here and use

String regex = "map-class frame-relay TempMap_1.*(?:\\R\\h+.*)*";

See the regex demo. Do NOT use Pattern.DOTALL with this pattern.

Details

  • map-class frame-relay TempMap_1 - a literal substring
  • .* - the rest of the line
  • (?:\\R\\h+.*)* - 0+ consecutive sequences of:
    • \\R - a line break sequence (in Java 7, use (?:\r\n?|\n), it should suffice)
    • \\h+ - 1+ horizontal whitespaces (in Java 7, use [^\\S\r\n]+)
    • .* - the rest of the line.

Java demo:

String s = "!\nmap-class frame-relay TempMap_1\n frame-relay cir 1536000\n frame-relay bc 15360\n frame-relay mincir 281000\n frame-relay adaptive-shaping becn\n service-policy output AB_TEMP_F1536K_0-256K-384K-128K_18\nlogging trap debugging\nlogging source-interface Loopback1\nlogging 136.91.111.21";
Pattern p = Pattern.compile("map-class frame-relay TempMap_1.*(?:\\R\\h+.*)*");
Matcher m = p.matcher(s);
List<String> res = new ArrayList<>();
while(m.find()) {
    res.add(m.group());
}
System.out.println(res);

Output:

[map-class frame-relay TempMap_1
 frame-relay cir 1536000
 frame-relay bc 15360
 frame-relay mincir 281000
 frame-relay adaptive-shaping becn
 service-policy output AB_TEMP_F1536K_0-256K-384K-128K_18]

Upvotes: 2

Related Questions