使用正则表达式从[,]中提取值

时间:2021-07-16 13:05:48

I have a scenario like whenever I get a string like [ 1234abcd , 5678efgh ], I want to get the values between [ , ] . I am using java split with a delimitter ",". With this I'm also getting [ and ], which I don't want.

我有一个场景,比如每当我得到像[1234abcd,5678efgh]这样的字符串时,我想得到[,]之间的值。我正在使用带分隔符“,”的java split。有了这个,我也得到[和],我不想要。

Any suggestions ?

有什么建议么 ?

2 个解决方案

#1


2  

Before split first get substring like this:

在拆分之前首先获取子串如下:

str.substring(1, str.length()-1)

then use split method.

然后使用split方法。

Demo example:

演示示例:

 public class StringDemo {
        public static void main(String[] args) {
            String str = "[ 1234abcd , 3456efgh]";
            str = str.substring(1, str.length()-1);
            String AfterSplit[] = str.split(",");
            System.out.println(AfterSplit[0]+"  "+AfterSplit[1]);
        }
    }

Output :

输出:

1234abcd    3456efgh 

#2


0  

(?<=\\[).*?(?=\\])

You can simply grab the middle content and then split by ,.See demo.

你可以简单地抓住中间内容然后拆分,参见演示。

https://regex101.com/r/hR7tH4/7

https://regex101.com/r/hR7tH4/7

#1


2  

Before split first get substring like this:

在拆分之前首先获取子串如下:

str.substring(1, str.length()-1)

then use split method.

然后使用split方法。

Demo example:

演示示例:

 public class StringDemo {
        public static void main(String[] args) {
            String str = "[ 1234abcd , 3456efgh]";
            str = str.substring(1, str.length()-1);
            String AfterSplit[] = str.split(",");
            System.out.println(AfterSplit[0]+"  "+AfterSplit[1]);
        }
    }

Output :

输出:

1234abcd    3456efgh 

#2


0  

(?<=\\[).*?(?=\\])

You can simply grab the middle content and then split by ,.See demo.

你可以简单地抓住中间内容然后拆分,参见演示。

https://regex101.com/r/hR7tH4/7

https://regex101.com/r/hR7tH4/7