简体   繁体   English

如何在 Java 中使用 Pattern 拆分字符串

[英]How to split a string using Pattern in Java

I want to split a string using methods in Pattern,here is what i did我想使用模式中的方法拆分字符串,这就是我所做的

String s = "[[[0.093493,51.6037],[0.091015,51.5956]]]"
Pattern branchPattern = Pattern.compile("[...]");
String[] split = branchPattern.split(s);

I want to get the result that String[] contains [0.093493,51.6037] and [0.091015,51.5956].我想得到 String[] 包含 [0.093493,51.6037] 和 [0.091015,51.5956] 的结果。 But the result of this code is not the result i want.但是这段代码的结果不是我想要的结果。 How can i split this string?我怎样才能拆分这个字符串? Or is there any way like use matcher to split this string in the format i want?或者有什么方法可以使用匹配器以我想要的格式拆分这个字符串?

Just do matching instead of splitting.只需进行匹配而不是拆分。

Pattern p = Pattern.compile("\\[[^\\[\\]]+\\]");
Matcher m = p.matcher(s);
while(m.find())
{
System.out.println(m.group());
}

DEMO演示

or或者

string.replaceAll("^\\[{2}|\\]{2}$", "").split(",(?=\\[)");

or或者

string.replaceAll("^\\[+|\\]+$", "").split("\\],\\[)");

I am trying to answer with another perspective.我试图从另一个角度来回答。 Have a look.Suppose you have placed parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#.看一看。假设您在两个特殊字符之间放置了参数,例如:#parameter# 或parameter或什至一次两个不同的符号,例如 *paramter#。 We can have list of all these parameters between those signs by this code :我们可以通过以下代码在这些标志之间列出所有这些参数:

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

public class Splitter {

    public static void main(String[] args) {

        String pattern1 = "#";
        String pattern2 = "#";
        String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";

        Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList parameters = new ArrayList<>();
            parameters.add(m.group(1));
            System.out.println(parameters);
            ArrayList result = new ArrayList<>();
            result.add(parameters);
            // System.out.println(result.size());
        }

    }
}

Here list result will have parameters n1_1,n2_2,n4_4.这里列表结果将有参数 n1_1,n2_2,n4_4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM