How to search text between brackets using regex using java?

Using Java How to search for text between brackets in expressions like "Request ECUReset for [*11 01]"

I want to extract "11 01" but I don’t know exactly the length of the text between the brackets.

can be: "Request ECUReset for [*11 01]" or: "Request ECUReset for [*11]" or: "Request ECUReset for [*11 01 10]" or any length

any help please ??

+4
source share
2 answers

If the strings are in fixed format, String#substring() will suffice:

Demo here.

 public static void main(String[] args) { String input1 = "Request ECUReset for [*11 01]"; String output1 = input1.substring(input1.indexOf("[*")+"[*".length(), input1.indexOf("]", input1.indexOf("[*"))); System.out.println(input1 + " --> " + output1); String input2 = "Request ECUReset for [*11]"; String output2 = input2.substring(input2.indexOf("[*")+"[*".length(), input2.indexOf("]", input2.indexOf("[*"))); System.out.println(input2 + " --> " + output2); String input3 = "Request ECUReset for [*11 01 10]"; String output3 = input3.substring(input3.indexOf("[*")+"[*".length(), input3.indexOf("]", input3.indexOf("[*"))); System.out.println(input3 + " --> " + output3); } 

Output:

 Request ECUReset for [*11 01] --> 11 01 Request ECUReset for [*11] --> 11 Request ECUReset for [*11 01 10] --> 11 01 10 



Or, if the input is less stable, you can use Regex (via the Pattern class utility) to match the number between the brackets:

Online demo here

 import java.util.regex.*; public class PatternBracket { public static void main(String[] args) { String input1 = "Request ECUReset for [*11 01]"; String output1 = getBracketValue(input1); System.out.println(input1 + " --> " + output1); String input2 = "Request ECUReset for [*11]"; String output2 = getBracketValue(input2); System.out.println(input2 + " --> " + output2); String input3 = "Request ECUReset for [*11 01 10]"; String output3 = getBracketValue(input3); System.out.println(input3 + " --> " + output3); } private static String getBracketValue(String input) { Matcher m = Pattern.compile("(?<=\\[\\*)[^\\]]*(?=\\])").matcher(input); if (m.find()) { return m.group(); } return null; } } 

(same conclusion as above)

+1
source

Assuming you don’t have nested brackets and want to ignore * after [ , you can use, for example, groups such as in this example

 String data="Request ECUReset for [*11 01]"; Matcher m=Pattern.compile("\\[\\*?(.*?)\\]").matcher(data); while (m.find()){ System.out.println(m.group(1)); } 

In addition, if you know that you have only one relevant part, you can use a single line

 System.out.println(data.replaceAll(".*\\[\\*?(.*?)\\].*", "$1")); 
0
source

Source: https://habr.com/ru/post/1488997/


All Articles