user3554654
user3554654

Reputation: 33

Taking specific substrings from a string

I have a long string like:

"[text1] [text2] [text3] [text4] [Text5] % & / !"

How one would go about inserting only substrings encapsulated in [] into an arrayList. So that symbols outside like the % & / ! would not get inserted?

Upvotes: 1

Views: 57

Answers (2)

abagshaw
abagshaw

Reputation: 6582

Use regex - this should work for you:

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexSquareBrackets{
    public static void main(String[] args) {
        String input = "[text1] [text2] [text3] [text4] [Text5] % & / !";

        Pattern pattern = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(input);
        ArrayList<String> output = new ArrayList<String>();
        while (matcher.find())
            output.add(matcher.group(1));

        //Print the items out
        System.out.println("Found Text: " + output);
    }
}

You will then have the items: "text1", "text2", "text3", "text4", "Text5" in your ArrayList output.

Upvotes: 2

Federico Piazza
Federico Piazza

Reputation: 30985

You can use a regex to do that like this:

\[(\w+)\]

So, you can have a code like this:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

       // String to be scanned to find the pattern.
       String line = "[text1] [text2] [text3] [text4] [Text5] % & / !";

       Pattern r = Pattern.compile("\\[(\\w+)\\]");
       List<String> tagList = new ArrayList<String>();

       // Now create matcher object.
       Matcher m = r.matcher(line);
       while (m.find()) {
          tagList.add(m.group(1));
       }

       System.out.println("Found tags: " + Arrays.toString(tagList.toArray()));
       //Output:
       //Found tags: [text1, text2, text3, text4, Text5]
    } 
}

Upvotes: 0

Related Questions