wykopowiedz
wykopowiedz

Reputation: 91

Substring first, second, third, ... , n match

Given: String s = "{aaa}{bbb}ccc.

How to get an array (or list) which elements will be:

0th element: aaa
1st element: bbb
2nd element: ccc

This is my try:

String x = "{aaa}{b}c";
return Arrays.stream(x.split("\\}"))
.map(ss -> {
    Pattern pattern = Pattern.compile("\\w*");
Matcher matcher = pattern.matcher(ss);
matcher.find();
return matcher.group();
})
.toArray(String[]::new);

(assume only Java <= 8 allowed)

Upvotes: 0

Views: 160

Answers (3)

Eritrean
Eritrean

Reputation: 16498

A simple replace should be enough if your strings are well formed like your examples:

String[] myStrings = {"{aaa}bbb", "{aaa}{bbb}{ccc}ddd", "{aaa}{bbb}{ccc}{ddd}eee"};
for(String str : myStrings){
    String[] splited = str.replace("}{", "}").replace("{", "").split("}");
    System.out.println(Arrays.toString(splited));
}

prints:

[aaa, bbb]
[aaa, bbb, ccc, ddd]
[aaa, bbb, ccc, ddd, eee]

Upvotes: 1

Daniel
Daniel

Reputation: 7724

This way is a bit simpler than using regex (and may be a bit faster too):

String[] strings = new String[100];
int index = 0;
int last = 0;
for(int i = 1; i < s.length(); i++){
    if(s.charAt(i) == "}"){
        strings[index++] = s.substring(last + 1, i - 1);
        last = i + 1;
    }
}
strings[index++] = s.substring(last, s.length());

If you want to use regex, the pattern needs to identify sequences of one or more letters, you can try the pattern (?:{([a-z]+)})*([a-z]+).

Upvotes: 1

Optional
Optional

Reputation: 4507

private static List<String> parse ()
  {
    String x = "{aaa}{b}c";
    Pattern pattern = Pattern.compile ("[^{\\}]+(?=})");
    List < String > allMatches = new ArrayList < String > ();
    Matcher m = pattern.matcher (x);
    while (m.find ())
      {
            allMatches.add (m.group ());
      }
      String lastPart = x.substring(x.lastIndexOf("}")+1);
      allMatches.add(lastPart);
      System.out.println (allMatches);

    return allMatches
  }

Make sure you do a check for lastIndexOf >-1, if your string may or may not contain last part without braces.

Upvotes: 1

Related Questions