GLinBoy
GLinBoy

Reputation: 676

use regex in String.Split() for extract text between { and } in java

I have a string like this:

String str = ${farsiName} - {symbolName}

I want to use split method to find and extract farsiName & symbolName from this string with regex. I found this solution https://stackoverflow.com/a/4006273/2670847 for doing something like this:

String in = "Item(s): [item1.test],[item2.qa],[item3.production]";

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);

while(m.find()) {
    System.out.println(m.group(1));
}

But I want to know, can I use similar regex for split method in String class?

Upvotes: 1

Views: 1097

Answers (3)

shams iit
shams iit

Reputation: 26

public static void main(String[] args){
    String n ="${farstName} - {symbolName}";
    String arr[] = n.split(" - ");
    for(String s : arr){
        System.out.println(s.replace("$", "").replace("{", "").replace("}", ""));
    }
}

Use this code.It will work.But I recommend regex.

Upvotes: 0

dumbPotato21
dumbPotato21

Reputation: 5695

Note : I do not recommend this. A regex would be much more versatile, and powerful.

String n ="${farsiName} - {symbolName}";
String s[] = n.split(" - ");
for(String x : s){
    System.out.println(x.replace("$", "").replace("{", "").replace("}", ""));
}

Upvotes: 0

Rudrani Angira
Rudrani Angira

Reputation: 986

You are on right track. Just replace the brackets and string.

String n ="${farsiName} - {symbolName}";

Pattern p = Pattern.compile("\\{(.*?)\\}");
Matcher m = p.matcher(n);

while(m.find()) {
    System.out.println(m.group(1));
}

Upvotes: 1

Related Questions