0

i need to split a string in java and map it to city ,country and continent

String s = "mumbai| india - Asia";
String b ="{city}|{country}-{Continent}"

where: | and - are special characters

output:

city - mumbai
country - india
continent - Asia
6
  • 3
    What you tried... Post your tried code Commented Jan 8, 2015 at 6:20
  • Is there a space between | and india, or is this a typo? Commented Jan 8, 2015 at 6:22
  • yes there can be space. My Logic is this<br> 1) using regex get a separator<br> 2) extract the text from string s 3) using regex get mapping from b and the produce the output Commented Jan 8, 2015 at 6:24
  • 1
    Should be straightforward using one regex with three capture groups. Commented Jan 8, 2015 at 6:26
  • @user3205867 why you do not use replace? "| " ---> "|" and " - " --->"-" Commented Jan 8, 2015 at 6:32

3 Answers 3

2

why dont you use named capturing groups ?

(?<city>[^|]*)\s*\|\s*(?<country>[^-]*)-\s*(?<continent>[\w\s]*)

demo here :

https://regex101.com/r/kZ4tQ7/1

see the match information on the right hand side

Sign up to request clarification or add additional context in comments.

1 Comment

Nice regex-page! Been looking for something similar for ages.
0

You Can try

String s = "mumbai| india - Asia";
String[] splitString = s.split("|");
String city = spiltString[0];
String secondSplit[] = splitString[1].split(" - ");
String country = secondSplit[0];
String continent = secondSplit[1];

Comments

0
 Try this.

 String s = "mumbai| india - Asia";
 String b ="{city}|{country}-{Continent}";

 String city = s.split("\\|")[0];
 String country = s.split("\\|")[1].split("-")[0];
 String cont =s.split("\\|")[1].split("-")[1];


 String cityT = b.split("\\|")[0];
 String countryT = b.split("\\|")[1].split("-")[0];
 String contT =b.split("\\|")[1].split("-")[1];



System.out.println(cityT.replace("{", "").replace("}", "") +" - " + city); 
System.out.println(countryT.replace("{", "").replace("}", "") +" - " +  country); 
System.out.println(contT.replace("{", "").replace("}", "") +" - " + cont); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.