1

How could I turn this String into two different variables from a pattern?

String: "[ADDRESS] Custom address n 1"
Variable type would be "ADDRESS" and variable field would be "Custom address n 1".
Is it possible without having a complicated loop checking for each character?

Coder12432f
  • 27
  • 1
  • 7
  • 3
    Use regex parsing. One way would be to use a regex to parse the string into two groups, one containing "[...] " and the other containing the rest. Then you would be able to extract the parts into whatever you wish. – filpa Jul 24 '18 at 20:21
  • `"ADDRESS Custom address n 1".split(" ", 2)` – Youcef LAIDANI Jul 24 '18 at 20:21
  • `type` = anything inside `[]` (excluding them). `field` = the rest – x80486 Jul 24 '18 at 20:22
  • Use simple regex to get the info from the pattern. See https://stackoverflow.com/questions/49246669/using-split-method-in-java-to-separate-different-inputs/49265943#49265943 – Jasper Huzen Jul 24 '18 at 20:24

2 Answers2

5

You can use regex with capturing groups:

Pattern p = Pattern.compile("\\[(.*)\\] (.*)");
Matcher m = p.matcher("[ADDRESS] Custom address n 1");
if (m.find()) {
    String type = m.group(1);
    String field = m.group(2);
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • @Andreas Would `.*?` have the same benefit? – shmosel Jul 24 '18 at 20:49
  • @shmosel No, but better than `.*`, since `.*` goes all the way to the end, then backtracks from there. According to regex101, `\[(.*)\] (.*)` is 50 steps, `\[(.*?)\] (.*)` is 24 steps, and `\[([^\]]*)\] (.*)` is 10 steps. – Andreas Jul 24 '18 at 20:59
2

You should be using this regex:

\[([^\]]*)\](.*)

For the String "[ADDRESS] Custom address n 1",

  • Group 1 would be "ADDRESS"
  • Group 2 would be "Custom address n 1"
jaudo
  • 2,022
  • 4
  • 28
  • 48