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)
source share