RP89
RP89

Reputation: 141

Java Regular expression to extract text from square bracket

How can I extract the text with in square brackets if it contains only dot and no other special character? For example I want to extract "com.package.file" from

 "ERR|appLogger|[Manager|Request]RequestFailed[com.package.file]uploading[com.file_upload]"

Upvotes: 2

Views: 1571

Answers (2)

João Silva
João Silva

Reputation: 91299

String s = "ERR|appLogger|[Manager|Request]RequestFailed[com.package.file]uploading[com.file]";
Pattern pattern = Pattern.compile("\\[([A-Za-z0-9.]+)\\]");
Matcher m = pattern.matcher(s);
if (m.find()) {
    System.out.println(m.group(1)); // com.package.file
}

Upvotes: 2

everag
everag

Reputation: 7662

Something in the lines of:

^\w+\|\w+\|\[\w+\|\w+\]\w+\[([\w\.]+)\]\w+\[[\w\.\_]+\]$

Would allow you to capture that.

Pattern pattern = Pattern.compile("^\\w+\\|\\w+\\|\\[\\w+\\|\\w+\\]\\w+\\[([\\w\\.]+)\\]\\w+\\[[\\w\\.\\_]+\\]$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("ERR|appLogger|[Manager|Request]RequestFailed[com.package.file]uploading[com.file_upload]");
System.out.println(matcher.group(1));

Upvotes: 0

Related Questions