Split the get the value using java [duplicate] - java

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have a reply message in a String and I want to split it to extract a value.
My String reply message format is:
REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...);
My requirement is to get the value ABC024049364194 from the above string format.
I tried using this code, but it hasn't worked:
String[] arrOfStr = str.split(",", 5);
for (String a : arrOfStr)
System.out.println(a);

If you split the String, you will simply need to access the token at index 2.
// <TYPE>(<ARGUMENTS>)
String message = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE);";
Matcher m = Pattern.compile("(\\w+)\\((.+)\\)").matcher(message);
if (m.find()) {
String type = m.group(1);
String[] arguments = m.group(2).split(",");
System.out.println(type + " = " + arguments[2]); // REPLY = ABC024049364194
}

public static void main(String[] args) {
String str = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...)";
String code = str.split(",")[2];
System.out.println(code);
}
Will work if your code is always after 2 coma

Related

Remove Substring from the Original String [duplicate]

This question already has answers here:
How can I remove a substring from a given String?
(14 answers)
Closed 3 years ago.
I am attempting to remove a substring from the original string
code attempted:
String details = events.event_details.value[bi];
String details2 ="";
if(details.length()>70) {
details2 = details.substring(70);
details.replaceFirst(details2, " ");
}
You do not remove it, you overwrite it with spaces...
remove is: cut it off!
replace: replace it!
details2 = details.substring(61, 70);
this gives you 10 chars
details2 = details.substring(details.length-10, details.length);
last 10
if you want 60 spaces and then the last 10, you need to create a String with 60 spaces, and use above method to extract whatever you want
maybe use a StringBuffer for this...
StringBuffer strg = new StringBuffer();
String cut = details.substring(details.length-10, details.length);
IntStream.iterate(0, i -> i++).limit(60).forEach((a) -> strg.append(" "));
strg.append(cut);
System.out.println(strg.toString());
You have to save your result from replaceFirst(...) somewhere,
as example again in details:
details = details.replaceFirst(details2, "");
You can try this way-
String details2 ="";
String result = ""
if(details.length()>70) {
details2 = details.substring(70);
result = details.replaceFirst(details2, " ");
}
System.out.println(result);
Here need a String variable where contain that replace's result

How to split a string with value contains the delimiter also in java? [duplicate]

This question already has answers here:
Java: splitting a comma-separated string but ignoring commas in quotes
(12 answers)
Closed 5 years ago.
I have a string with value - String sData = "abc|def|\"de|er\"|123"; and I will need to split it with delimiter - "|". In this case, my expected result will be
abc
def
"de|er"
123
Below is my code
String sData = "abc|def|\"de|er\"|123";
String[] aSplit = sData.split(sDelimiter);
for(String s : aSplit) {
System.out.println(s);
}
But it actually comes out the below result
abc
def
"de
er"
123
I have tried with this pattern - String sData = "abc|def|\"de\\|er\"|123"; but it's still not returning my expected result.
Any idea how can I achieve my expected result?
This worked for me:
String sData = "abc|def|\"de|er\"|123";
String[] aSplit = sData.split("\\|");
for(int i = 0; i < aSplit.length; i++) {
if(aSplit[i].startsWith("\"")) {
if(aSplit[i+1].endsWith("\"")) {
aSplit[i] = aSplit[i] + "|" + aSplit[i+1];
aSplit[i+1] = "";
}
}
}
for(String s : aSplit) {
if(!s.equals(""))
System.out.println(s);
}
The output:
abc
def
"de|er"
123

Splitting the string in java is giving different results than expected [duplicate]

This question already has answers here:
Split string on spaces in Java, except if between quotes (i.e. treat \"hello world\" as one token) [duplicate]
(1 answer)
Tokenizing a String but ignoring delimiters within quotes
(14 answers)
Closed 6 years ago.
Hi I am new to Java and trying to use the split method provided by java.
The input is a String in the following format
broadcast message "Shubham Agiwal"
The desired output requirement is to get an array with the following elements
["broadcast","message","Shubham Agiwal"]
My code is as follows
String str="broadcast message \"Shubham Agiwal\"";
for(int i=0;i<str.split(" ").length;i++){
System.out.println(str.split(" ")[i]);
}
The output I obtained from the above code is
["broadcast","message","\"Shubham","Agiwal\""]
Can somebody let me what I need to change in my code to get the desired output as mentioned above?
this is hard to split string directly.So, i will use the '\t' to replace
the whitespace if the whitespace is out of "". My code is below, you can try it, and maybe others will have better solution, we can discuss it too.
package com.code.stackoverflow;
/**
* Created by jiangchao on 2016/10/24.
*/
public class Main {
public static void main(String args[]) {
String str="broadcast message \"Shubham Agiwal\"";
char []chs = str.toCharArray();
StringBuilder sb = new StringBuilder();
/*
* false: means that I am out of the ""
* true: means that I am in the ""
*/
boolean flag = false;
for (Character c : chs) {
if (c == '\"') {
flag = !flag;
continue;
}
if (flag == false && c == ' ') {
sb.append("\t");
continue;
}
sb.append(c);
}
String []strs = sb.toString().split("\t");
for (String s : strs) {
System.out.println(s);
}
}
}
This is tedious but it works. The only problem is that if the whitespace in quotes is a tab or other white space delimiter it gets replaced with a space character.
String str = "broadcast message \"Shubham Agiwal\" better \"Hello java World\"";
Scanner scanner = new Scanner(str).useDelimiter("\\s");
while(scanner.hasNext()) {
String token = scanner.next();
if ( token.startsWith("\"")) { //Concatenate until we see a closing quote
token = token.substring(1);
String nextTokenInQuotes = null;
do {
nextTokenInQuotes = scanner.next();
token += " ";
token += nextTokenInQuotes;
}while(!nextTokenInQuotes.endsWith("\""));
token = token.substring(0,token.length()-1); //Get rid of trailing quote
}
System.out.println("Token is:" + token);
}
This produces the following output:
Token is:broadcast
Token is:message
Token is:Shubham Agiwal
Token is:better
Token is:Hello java World
public static void main(String[] arg){
String str = "broadcast message \"Shubham Agiwal\"";
//First split
String strs[] = str.split("\\s\"");
//Second split for the first part(Key part)
String[] first = strs[0].split(" ");
for(String st:first){
System.out.println(st);
}
//Append " in front of the last part(Value part)
System.out.println("\""+strs[1]);
}

Split String Having delimeter, but I need the delimeter at some places [duplicate]

This question already has answers here:
Currency values string split by comma
(3 answers)
Closed 7 years ago.
I need to split the string which contains amount like "1,000.00,106,924.31" . how to do this??
Peviously I have tried using split by ',' but it is giving me output as 1,000.00,106,924.31.
But i need output as 1,000.00 106,924.31.
You can something like this:
public static void main(String[] args) {
String amounts = "1,000.00,106,924.31";
List<String> results = new ArrayList<>();
do {
int indexOfFirstComma = amounts.indexOf(",");
String sub_amounts = amounts.substring(indexOfFirstComma+1);
String splitComma = sub_amounts.split(",")[0];
results.add(amounts.substring(0, indexOfFirstComma) + "," + splitComma);
if (sub_amounts.indexOf(",")>0) {
amounts = sub_amounts.substring(sub_amounts.indexOf(",")+1);
}else {
break;
}
}while (true);
results.forEach(System.out::println);
}

Extract date from a string [duplicate]

This question already has answers here:
Regex date format validation on Java
(12 answers)
Closed 8 years ago.
I would like to find date from java string.But i can not able to do this please help
String : 01-02-2014 <2>
Ineed output like :01-02-2014
My code:
public String rejex(String idate){
String result = null;
try{
String regex = "([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})";
result = idate.replaceAll(regex, "$1-$2-$3");
}catch(Exception e){}
return result;
}
You are replacing what you are after (the date segments) with themselves.
If you want to extract it, this will work:
String regex = "(([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})).*?<(\\d+)>";
String str = "This is a random string 01-02-2014 <123> this is another part of that random string";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println("Date: " + m.group(1));
System.out.println("Number: " + m.group(6));
}
Yields:
Date: 01-02-2014
Number: 123
just extract \\d\\d-\\d\\d-\\d{4} out, let SimpleDateFormat do the parsing job.
if space is there all the time then it's simple.
String dateStr = "01-02-2014 <2>"
String dateSplit[] = dateStr.split(" ");
//dateSplit[0] is what u are looking for
or
String dateStr = "01-02-2014 <2>"
String dateSplit[] = dateStr.split("<");
//dateSplit[0].trim() is what u are looking for
and then simply use SimpleDateFormat to converting it into Date.

Categories