Could someone give me suggestions for a regex for the below?
Example: city^chennai|country^India~TamilNadu|pincode^600034
Expected delimited String are:
city
chennai
country
India,TamilNadu
pincode
600034
Note: ~
should be converted into ,
Just split on non-word chars (excluding comma) after replacing the ~
with a comma:
input.replaceAll("~",",").split("[^\\w,]");
then (as per comment requiring a map) iterate over the resulting array in pairs, adding the map entries.
Here's some test code:
public static void main( String[] args ) {
String input = "city^chennai|country^India~TamilNadu|pincode^600034";
String[] things = input.replaceAll( "~", "," ).split( "[^\\w,]" );
Map<String, String> map = new HashMap<String, String>( );
for (int i = 0; i < things.length; i+=2) {
map.put(things[i], things[i+1]);
}
System.out.println( map );
}
Output:
{pincode=600034, country=India,TamilNadu, city=chennai}
((w+)[|^~])*(w+)
Edit: Now I noticed that it's map-like, so perhaps:
((w+)^(w+)|)*(w+)^(w+)
Replace w+ with custom class in [...]
to get ~ also working.
Pattern p = Pattern.compile("((w+)^(w+)|)*(w+)^(w+)");
Matcher m = p.matcher("city^chennai|country^India~TamilNadu|pincode^600034");
if( m.matches() ){
for( int i = 1; i < m.groupCount(); i+=2 ) {
// m.group(i) and m.group(i+1) gives you the values.
}
}
If you want the easier way, use Pattern#split("")
You can just use this:
.replaceAll("~", ",").split("[|^]")
Assume the String is split up properly, you can group them into name-value pair by mapping the String at index 2k to index (2k + 1)
you can use StringTokenizer
class here to split a string with different delimiters. Use hasNextToken("delimiterHereAsString")
method to specify different delimiters with which you want to split.
this link might help you. http://www.java-examples.com/java-stringtokenizer---specify-delimiter-example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.