Does not work Regex for multiple string split in java? - java

I want to split string with multiple string delimiter.
For example :
String is "abc[11]xyz[86]pqr[87]sdv[11]adf[86]fgr[87]fadggthy"
Output :
abc
xyz
pqr
sdv
adf
fgr
fadggthy
I want to split string by "[11]" , "[86]" , "[87]"
Tried following code but does not work.
void testSplit() {
StringBuilder message = new StringBuilder("abc[11]xyz[86]pqr[87]sdv[11]adf[86]fgr[87]fadggthy");
Map<String, String> replaceStringMap = new HashMap();
replaceStringMap.put("\\\\[11\\\\]", "11");
replaceStringMap.put("\\\\[86\\\\]", "86");
replaceStringMap.put("\\\\[87\\\\]", "87");
String starter = "(";
String middle = ")|(";
String end = ")";
Set<String> keySet = replaceStringMap.keySet();
boolean isFirst = true;
StringBuilder regex = new StringBuilder(starter);
Iterator<String> itr = keySet.iterator();
while(itr.hasNext()) {
String string = itr.next();
if(itr.hasNext()) {
regex.append(string);
regex.append(middle);
} else {
regex.append(string);
regex.append(end);
}
}
System.out.println(regex.toString());
String[] strings = message.toString().split(regex.toString());
for(String s : strings) {
System.out.println(s);
}
}
Output :
(\\[87\\])|(\\[11\\])|(\\[86\\])
abc[11]xyz[86]pqr[87]sdv[11]adf[86]fgr[87]fadggthy
Output:abc[11]xyz[86]pqr[87]sdv[11]adf[86]fgr[87]fadggthy
Expected Output:
abc
xyz
pqr
sdv
adf
fgr
fadggthy
Below Code works :
String regex = "(\\[87\\])|(\\[11\\])|(\\[86\\])";
Here if i hardcode regex then it works but when i generate regex dynamically by reading value from map then it does not work.
Problem is that i can't generate regex at dynamic level.

You have an extra pair of \ in your delimeters.
Given this:
StringBuilder message = new StringBuilder("abc[11]xyz[86]pqr[87]sdv[11]adf[86]fgr[87]fadggthy");
Map<String, String> replaceStringMap = new HashMap();
replaceStringMap.put("\\[11\\]", "11");
replaceStringMap.put("\\[86\\]", "86");
replaceStringMap.put("\\[87\\]", "87");
String starter = "(";
String middle = ")|(";
String end = ")";
Set<String> keySet = replaceStringMap.keySet();
boolean isFirst = true;
StringBuilder regex = new StringBuilder(starter);
Iterator<String> itr = keySet.iterator();
while (itr.hasNext()) {
String string = itr.next();
if (itr.hasNext()) {
regex.append(string);
regex.append(middle);
} else {
regex.append(string);
regex.append(end);
}
}
System.out.println(regex.toString());
String[] strings = message.toString().split(regex.toString());
for (String s : strings) {
System.out.println(s);
}
}
It yields this:
(\[86\])|(\[87\])|(\[11\])
abc
xyz
pqr
sdv
adf
fgr
fadggthy

A general solution, for any value between [] considered as separator:
String test = abc[11]xyz[86]pqr[87]sdv[11]adf[86]fgr[87]fadggthy
String r = "(\\[[^\\]]*\\])"
for(String part : test.split(r)) println(part)
> abc
> xyz
> pqr
> sdv
> adf
> fgr
> fadggthy

Related

Splitting a string for last occurrence a character

I'm trying to split a String with a format like this :
"abc=cde,dfe=lk,f,sss=f,d,s"
I'd like to recover these values in a map by using the first set of characters as a key and the second ones as value.
For example
key: abc, value: cde
key: dfe, value: lk,f
key: sss, value: f,d,s
So splitting these values for the last occurrence of ",".
Any ideas on how to do it?
I tried with regex and Stringtokenizer but I can't manage to recover just the last occurrence of ","
You could use the following regex (could possibly be optimized):
,(?=(?:(?!,).)*=)
(see on Regex101)
This matches a , which has no subsequent , until the next =.
You need to use regex for this.
Full Code :
public class Test {
public static void main(String args[]) {
String input = "abc=cde,dfe=lk,f,sss=f,d,s";
String[] arrOfStr = input.split(",(?=(?:(?!,).)*=)");
HashMap<String, String> properties = new HashMap<String, String>();
for(int i=0;i<arrOfStr.length;i++) {
String[] temp = arrOfStr[i].split("=");
properties.put(temp[0], temp[1]);
}
System.out.println("Input String : " +input);
System.out.println("\nFinal properties : ");
properties.entrySet().forEach(entry->{
System.out.println("key = " +entry.getKey() + " :: value = " + entry.getValue());
});
}
}
Output :
Input String : abc=cde,dfe=lk,f,sss=f,d,s
Final properties :
key = dfe :: value = lk,f
key = sss :: value = f,d,s
key = abc :: value = cde
Full Code :
public class Test {
public static void main(String args[]) {
String text = "abc=cde,dfe=lk,f,sss=f,d,s";
String[] parts = text.split(",");
Map<String, String> map = new LinkedHashMap<>();
String key = null;
StringBuilder value = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (parts[i].contains("=")) {
if (key != null) {
map.put(key, value.toString());
value.setLength(0);
}
String[] innerParts = parts[i].split("=");
key = innerParts[0];
value.append(innerParts[1]);
} else {
value.append(',').append(parts[i]);
}
}
map.put(key, value.toString());
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
}
}
Output :
abc=cde
dfe=lk,f
sss=f,d,s

REGEX to replace numbers with String

I have a String as below:
((((1 OR 2) AND 3) OR 11) AND 23)
I want to replace numbers with String values.
I am new to regex and unable to figure out how to replace numbers lying within a range.
Here is my code to resolve your problem. My poor regex knowlodge was not enough to resolve by only using regex.
public static void main(String[] args)
{
String temp = "(X)+|";
String regex = "";
String text = "((((1 OR 2) AND 3) OR 11) AND 23)";
Map<String, String> numberToString = new TreeMap<>((o1, o2) -> Integer.valueOf(o2) - Integer.valueOf(o1));
numberToString.put("3", "THREE");
numberToString.put("2", "TWO");
numberToString.put("1", "ONE");
numberToString.put("11", "ELEVEN");
numberToString.put("23", "TWENTYTHREE");
for(String number : numberToString.keySet()){
regex = regex + temp.replace("X", number);
}
regex = regex.substring(0, regex.lastIndexOf('|'));
Set<String> allMatches = new TreeSet<>((o1, o2) -> Integer.valueOf(o2) - Integer.valueOf(o1));
Matcher m = Pattern.compile(regex).matcher(text);
while (m.find()) {
allMatches.add(m.group());
}
for (String match : allMatches) {
if (numberToString.get(match) != null)
text = text.replaceAll(match, numberToString.get(match));
}
System.out.println(text);
System.out.println(regex);
}
Use str.replaceAll(1, "one"); function

How to split a String in java based on integers and return as String Array

I have a sting like this:
String str = "Aseff1deffre78ijnntke909nnkdhfkk9kshgfks2";
I want to split this string where the integer is occurred while reading and
store the split Strings in an Array of Strings
Please try the following:
public static String[] splitBasedOnInteger(String str) {
String str2[] = str.split("\\d+");
for (String s : str2) {
System.out.println(s);
}
return str2;
Pattern p = Pattern.compile("[A-Za-z]+");
Matcher m = p.matcher("Aseff1deffre78ijnntke909nnkdhfkk9kshgfks2");
List<String> resultList = new ArrayList<String>();
while (m.find()) {
resultList.add(m.group());
}
String[] arr = resultList.toArray(new String[resultList.size()]);

Convert value in string into hashmap?

I have a string where i have multiple values. The key and value are separated by * and the whole value is separated by $.
Below is the example:
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
And now I want to put the value of this into hashmap in key value pair.
Below is the code i was using but didnt work for converting it into hashmap. Please guide.
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String []tmp = StringUtils.split(agf,'*');
for (String v : tmp) {
String[] t = StringUtils.split(v,'$');
map.put(t[0], t[1]);
}
import java.util.HashMap;
import java.util.Map;
public class Parse{
public static void main(String ...args){
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String [] split = agf.split("\\$");
Map<String,String> map = new HashMap<String,String>();
for(String temp : split){
String [] tempo = temp.split("\\*");
map.put(tempo[0],tempo[1]);
}
for(String mapkeys : map.keySet()){
System.out.println(mapkeys+" ::: "+map.get(mapkeys));
}
}
}
if you had multiple values for a given key then use this:
public static void main(String ...args){
String agf = "abc*pqr*gas$sfd*ghn$atr*mnb$tre*fgt";
String [] split = agf.split("\\$");
Map<String,String> map = new HashMap<String,String>();
for(String temp : split){
String [] tempo = temp.split("\\*");
StringJoiner sj = new StringJoiner(",");
for(int i = 1; i < tempo.length;i++){
sj.add(tempo[i]);
}
String value = sj.toString();
map.put(tempo[0],value);
}
for(String mapkeys : map.keySet()){
System.out.println(mapkeys+" ::: "+map.get(mapkeys));
}
}
Hope you found this helpful
Looking at your example string, you should be splitting first on $ (to get individual key value pairs) and then on * (to separate key and values)
Switch '*' and '$'.
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String []tmp = StringUtils.split(agf,'$');
for (String v : tmp) {
String[] t = StringUtils.split(v,'*');
map.put(t[0], t[1]);
}
Use string.split("//$") and string.split("//*") as regex for your use case.
Full code :
String str = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String[] entries = str.split("\\$");
Map<String, String> map = new HashMap<String, String>();
for (int i=0; i<entries.length; i++) {
String[] entry = entries[i].split("\\*");
map.put(entry[0], entry[1]);
}
System.out.println("Entries are -> " + map.entrySet());
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
\\next array will contain such elements: "abc*pqr", "sfd*ghn", "atr*mnb", "tre*fgt"
String[] pairs = agf.split("\\$");
Map<String, String> map = new HashMap();
for (String pair: pairs) {
\\in first iteration next array will contain such elements: "abc", "pqr"
String[] t = pair.split("\\*");
\\just fill out map with data
map.put(t[0], t[1]);
}

How to Split this String and store in HashMap

String str = "id1;;name1 || id2;;name2 || id3;;name3||";
into id1 name1 ...and then store it in hashmap as id1 - key , name1- value
id2 - key , name2 - value
......
One way to reach your goal is to use a StringTokenizer.
Code example:
public static void main(String[] args) {
String input = "id1;;name1 || id2;;name2 || id3;;name3||";
Map<String, String> map = new HashMap<>();
// You have to split two times
for (String outer : splitBy(input, " || ")) {
List<String> inner = splitBy(outer, ";;"); // for example: outer="id1;;name1"
// Make sure, you have two inner input-elements
if (inner.size() == 2) {
String key = inner.get(0); // First element of List = Key
String value = inner.get(1); // Second element of List = Value
map.put(key, value);
}
}
}
private static List<String> splitBy(String toSplit, String delimiter) {
List<String> tokens = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(toSplit, delimiter);
while (tokenizer.hasMoreTokens()) {
tokens.add(tokenizer.nextToken());
}
return tokens;
}
Also take a look at this: Scanner vs. StringTokenizer vs. String.Split
for this particular case you should do something like this:
Map<String, String> yourHashMap = new HashMap<String, String>();
String input = "id1;;name1 || id2;;name2 || id3;;name3||";
// "\" is special character so it need an escape
String[] yourStrings = input.split("\\|\\|");
String[] hashObject = new String[2];
for (int i = 0; i <= yourStrings.length - 1; i++) {
//fist you have to remove the whitespaces
yourStrings[i] = yourStrings[i].replaceAll("\\s+", "");
hashObject = yourStrings[i].split(";;");
yourHashMap.put(hashObject[0], hashObject[1]);
}
Your input string have a strange format, I recommend you to change it.

Categories