Extracting fields name from single string using split method - java

I have a string variable that I want to extract some words from. These words are field names that I am going to need.Currently, I'm using the split method to split string into array.
String whereClause = "id=? AND name=?";
String[] results = whereClause.split("[=?]");
In this case I am only interesting in getting an array containing "id" and "name" but what I'm getting is [id, , AND name]. This also gets " " and the word "AND". How can I reconstruct this to accomplish what I'm trying to do or is there a better way to accomplish this?

You could do matching instead os splitting.
String s = "id=? AND name=?";
Matcher m = Pattern.compile("[^\\s=?]+(?=[=?])").matcher(s);
while(m.find()){
System.out.println(m.group());
}
[^\\s=?]+ matches any character but not of a space or = or ? chars, one or more times.
Output:
id
name
OR
Create a new Array list and then append the matched results to that.
ArrayList<String> list = new ArrayList<String>();
String s = "id=? AND name=?";
Matcher m = Pattern.compile("[^\\s=?]+(?=[=?])").matcher(s);
while(m.find()){
list.add(m.group());
}
System.out.println(list);
Output:
[id, name]

Split with blankspace
String whereClause = "id=? AND name=?";
String[] results = whereClause.split(" ");
for(String tempResult : results)
{
if(tempResul.indexOf("id")=-1)
{
// do your logic here
}
//same with other name
}

String whereClause = "id=? AND name=?";
String[] results = whereClause.split("[=?]");
System.out.println(results[0]);
System.out.println(results[2].substring(results[2].indexOf("AND")+4,results[2].length()));
Try this code,i am simply doing substring of the given string

Related

Transform string format to list - it is not a json format string

How to transform a string with this format into a list?
[[["Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"]],[["example","text","thanks"]],[["name","surname","age"]]]
From that string I would like to have 3 lists:
List 1:
"Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"
List 2:"example","text","thanks"
List 3:"name","surname","age"
I have tried different approachs do process this string, with split, with method StringUtils.substringBetween, with indexOf, with regex, with Json Parser.... I always get an error, is it an easier way out??
Comments: I don't see this string as a Json format, since the Json format would be "name":"John", If I'm wrong, please let me know how I could process it as a Json....
I have tried also with JsonParser and had the Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object:
[[["Census_county_divisions","Popula
I write this code:
remove the [[[,]]] strings
replace the ]],[[ for | character
split the string
///The String to convert
String arg = "[[[\"Census_county_divisions\",....
[[\"example\",\"text\",\"thanks\"]],[[\"name\",\"surname\",\"age\"]]]";
System.out.println(arg);
////Replace
arg = arg.replace("[[[", "");
arg = arg.replace("]],[[", "|");
arg = arg.replace("]]]", "");
System.out.println(arg);
////Split
String[] array=arg.split("\\|");
List<String> list = Arrays.asList(array);
///Verify
for(String s: list) {
System.out.println(s);
}
Regards
This worked for me. I only trimmed the start and end character set and then split it into 3 different strings which yielded the lists.
str = new StringBuilder(str).replace(0, 4, "")
.reverse().replace(0, 4, "")
.reverse()
.toString();
String[] arr1 = str.split("\"\\]\\],\\[\\[\"");
List<String> list1 = Arrays.asList(arr1[0]
.split("\",\""));
List<String> list2 = Arrays.asList(arr1[1]
.split("\",\""));
List<String> list3 = Arrays.asList(arr1[2]
.split("\",\""));
Maybe you could use Regex to extract everything inside the "[[" "]]" and trimming the "[" and "]" at the start and the end of each group. After that, you could split the result and put it into a List.
Here a simple example:
List<List<String>> lists = new ArrayList<>();
String string = "[[[\"Census_cunty_divisions\",\"Populated_places_in_the_United_States\",\"Populated_places_by_country\",\"Geography_by_country\",\"Geography_by_place\",\"Geography\",\"Main_topic_classifications\"]],[[\"example\",\"text\",\"thanks\"]],[[\"name\",\"surname\",\"age\"]]]";
Pattern pattern = Pattern.compile("\\[\\[(.*?)\\]\\]");
Matcher matcher = pattern.matcher(string);
String proccesed;
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
proccesed = StringUtils.strip(matcher.group(i), "[");
proccesed = StringUtils.strip(proccesed, "]");
lists.add(Arrays.asList(proccesed.split(",")));
}
}
int i = 0;
for(List<String> stringList : lists){
System.out.printf("List # %s \n", i);
for(String elementOfList:stringList){
System.out.printf("Element %s \n", elementOfList);
}
i++;
}
Here you will have a dynamic list depending on the initial String.
I've used the org.apache.commons commons-text library to strip the matches.
I hope it's useful.

java regex or other way for finding string between string and other parts of that string

I have a String like this
String s = "AZERTY<em>ZA</em> QWERTY OK <em>NE</em>NO ;
I want extract strings between and and construct a StringBuilder with all parts of the string in right order. I do this because i need to identify and localize the strings extracted but i need to keep the entire string too.
The purpose for all this work is to add later the entire String in a excel sheet cell and add font for the string between
XSSFRichTextString xssfrt = new XSSFRichTextString(); // acts like a StringBuilder
xssfrt .append("AZERTY");
xssfrt .append("ZA" , font); //extract 1
xssfrt .append(" QWERTY OK "); // keep spaces
xssfrt .append("NE" , font); //extract 2
xssfrt .append("NO");
There is my regex which can extract the desired strings but i don't know how to construct the StringBuilder with all parts in right order :/
Pattern p = Pattern.compile("\\<em>(.*?)\\</em>");
Matcher m = p.matcher(value);
while(m.find())
{
m.group(1); //extracts
}
Thank you very much
An easy fix is too add another group to match a string before <em>:
Pattern p = Pattern.compile("(.*?)<em>(.*?)</em>");
With it, m.group(1) refers to the string outside em, and m.group(2) is the one inside.
Of course, this won't include the last string outside em (NO in your example). So, you might want to memorize the last index where the matching ends with e.g. int end = m.end(), and retrieve it s.substring(end).
You can use Matcher's appendReplacement(StringBuffer sb, String replacement) and appendTail(StringBuffer sb) function to keep it in order. And have a list which will store the extracted Strings. Something like this
public static void main(String[] args) throws java.lang.Exception {
String s = "AZERTY<em>ZA</em> QWERTY OK <em>NE</em>NO";
String matchedString = null;
List<String> extractedString = new ArrayList<String>();
Pattern p = Pattern.compile("\\<em>(.*?)\\</em>");
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
matchedString = m.group(1);
extractedString.add(matchedString);
m.appendReplacement(sb, matchedString);
sb.append(" ");
}
m.appendTail(sb);
System.out.println(sb.toString());
System.out.println(extractedString.toString());
}
Output :
String buffer = AZERTYZA QWERTY OK NE NO
List of extracted String = [ZA, NE]
String[] pieces = s.split("<.*?>")
This will split the string on anything surrounded by <>.
If your tag is always em, then you can use:
String[] pieces = s.split("</?em>")
You need to do something like as :
String str = "AZERTY<em>ZA</em> QWERTY OK <em>NE</em>NO";
StringBuilder stringBuilder = new StringBuilder();
String[] parts = str.split("(<\\/?em>)");
System.out.println("parts : "+Arrays.toString(parts));
for(String s:parts){
System.out.println("Part going to append :"+s);
stringBuilder.append(s);
}
System.out.println("StringBuilder : "+stringBuilder.toString());
}
Out put will be:
> parts : [AZERTY, ZA, QWERTY OK , NE, NO] Part going to append :AZERTY
> Part going to append :ZA Part going to append : QWERTY OK Part going
> to append :NE Part going to append :NO StringBuilder : AZERTYZA QWERTY
> OK NENO
UPDATES :--
Check the updated code:
String str = "AZERTY<em>ZA</em> QWERTY OK <em>NE</em>NO";
//replace word in string which is preceded by <\em> to word:font eg. ZA:font
str = str.replaceAll("(\\w+)(?=\\<\\/em\\>)", "$1:font");
// After replace :AZERTY<em>ZA:font</em> QWERTY OK <em>NE:font</em>NO
String[] parts = str.split("(<\\/?em>)");
// After split : [AZERTY, ZA:font, QWERTY OK , NE:font, NO]
XSSFRichTextString xssfrt = new XSSFRichTextString();
for(String s:parts){
//set font according to replace string
if(s.contains(":")){
String[] subParts = s.split(":");
xssfrt.append(subParts[0], /**check the subParts[0] and set the font***/ );
}else{
xssfrt.append(s);
}
}
}

Check if id in string and get value if so

I am trying to get a regex to match, then get the value with it. For example, I want to check for 1234 as an id and if present, get the status (which is 0 in this case). Basically its id:status. Here is what I am trying:
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
if (topicStatus.matches(regex)) {
//How to get status?
}
Not only do I not know how to get the status without splitting and looping through, I don't know why it doesn't match the regex.
Any help would be appreciated. Thanks.
Use the Pattern class
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
Pattern MY_PATTERN = Pattern.compile(regex);
Matcher m = MY_PATTERN.matcher(topicStatus);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
}
The key here is to surround the position you want [0-2] in parenthesis which means it will be saved as the first group. You then access it through group(1)
I made some assumptions that your pairs we're always comma separate and then delimited by a colon. Using that I just used split.
String[] idsToCheck = topicStatus.split(",");
for(String idPair : idsToCheck)
{
String[] idPairArray = idPair.split(":");
if(idPairArray[0].equals(someId))
{
System.out.println("id : " + idPairArray[0]);
System.out.println("status: " + idPairArray[1]);
}
}

Java PatternSyntaxException when replacing characters in a String object

I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();

Convert string to array in Java?

I have a string which has the values like this (format is the same):
name:xxx
occupation:yyy
phone:zzz
I want to convert this into an array and get the occupation value using indexes.
Any suggestions?
Basically you would use Java's split() function:
String str = "Name:Glenn Occupation:Code_Monkey";
String[] temp = str.split(" ");
String[] name = temp[0].split(":");
String[] occupation = temp[1].split(":");
The resultant values would be:
name[0] - Name
name[1] - Glenn
occupation[0] - Occupation
occupation[1] - Code_Monkey
Read about Split functnio. You can split your text by " " and then by ":"
I would recommend using String's split function.
Sounds like you want to convert to a property Map rather than an array.
e.g.
String text = "name:xxx occupation:yyy phone:zzz";
Map<String, String> properties = new LinkedHashMap<String, String>();
for(String keyValue: text.trim().split(" +")) {
String[] parts = keyValue.split(":", 2);
properties.put(parts[0], parts[1]);
}
String name = properties.get("name"); // equals xxx
This approach allows your values to be in any order. If a key is missing, the get() will return null.
If you are only interested in the occupation value, you could do:
String s = "name:xxx occupation:yyy phone:zzz";
Pattern pattern = Pattern.compile(".*occupation:(\\S+).*");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
String occupation = matcher.group(1);
}
str = "name:xxx occupation:yyy phone:zzz
name:xx1 occupation:yy3 phone:zz3
name:xx2 occupation:yy1 phone:zz2"
name[0] = str.subtsring(str.indexAt("name:")+"name:".length,str.length-str.indexAt("occupation:"))
occupation[0] = str.subtsring(str.indexAt("occupation:"),str.length-str.indexAt("phone:"))
phone[0] = str.subtsring(str.indexAt("phone:"),str.length-str.indexAt("occupation:"))
I got the solution:
String[] temp= objValue.split("\n");
String[] temp1 = temp[1].split(":");
String Value = temp1[1].toString();
System.out.println(value);

Categories

Resources