문제

I have text which contains tags expressed in this format: [text other text].

I'd like to split the string using square brackets as separators, but this:

String.split("\\[|\\]");

This doesn't give expected results.

How can I do this?

도움이 되었습니까?

해결책

I'm not sure if one can do this with split(). With pattern finding and [^\\]]+ ("all symbols until the closing bracket") in your pattern this is quite straight-forward:

public static void main(String[] args) {
    String line = "xx [text other text], [jili u babusi dva veselikh gusya], " +
        "[a granny there was having two gay gooses] zz";

    Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(line);

    List<String> tags = new ArrayList<>();

    int pos = -1;
    while (matcher.find(pos+1)){
        pos = matcher.start();
        tags.add(matcher.group(1));
    }

    System.out.println(tags);
}

다른 팁

I know this was asked 4 years ago, but for anyone with the same/similar question that lands here (as I did), there is something even simpler than using regex:

String result = StringUtils.substringBetween(str, "[", "]");

In your example, result would be returned as "text other text", which you can further split using StringUtils.split() if needed. I would recommend the StringUtils library for various kinds of (relatively simple) string manipulation; it handles things like null input automatically, which can be convenient.

Documentation for substringBetween(): https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substringBetween-java.lang.String-java.lang.String-java.lang.String-

There are two other versions of this function, depending on whether the opening and closing delimiters are the same, and whether the delimiter(s) occur(s) in the target string multiple times.

You can use Pattern.quote("YOUR PATTERN GOES HERE"), as mentioned below,

str.split(Pattern.quote("["));

you can use the split method and put the answer in an array

String [] d = s.split("(\\[)|(\\])");

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top