Im using java and I have a String that I would like to parse which contains the following
Logging v0.12.4
and would like to split it into a String containing
Logging
and an integer array containing
0.12.4
where
array[i][0] = 0
and
array[i][1] = 12
and so on. I have been stuck on this for a while now.
split your string on space to get Logging and v0.12.4
remove (substring) v from v0.12.4
split 0.12.4 on dot (use split("\\.") since dot is special in regex)
you can also parse each "0" "12" "4" to integer (Integer.parseInt can be helpful).
You can use a regex or just normal String splitting
String myString = "Logging v0.12.4";
String[] parts = myString.split(" v");
// now parts[0] will be "Logging" and
// parts[1] will be "0.12.4";
Then do the same for the version part:
String[] versionParts = parts[1].split("\\.");
// versionParts[0] will be "0"
// versionParts[1] will be "12"
// versionParts[2] will be "4"
You can "convert" these to integers by using Integer.parseInt(...)
Here ya go buddy, because I'm feeling generous today:
String string = "Logging v0.12.4";
Matcher matcher = Pattern.compile("(.+?)\\s+v(.*)").matcher(string);
if (matcher.matches()) {
String name = matcher.group(1);
int[] versions = Arrays.stream(matcher.group(2).split("\\.")).mapToInt(Integer::parseInt).toArray();
}
Related
I am getting comma sepeated string in below format:
String codeList1 = "abc,pqr,100101,P101001,R108972";
or
String codeList2 = "mno, 100101,108972";
Expected Result : Check if code is numeric after removing first alphabet. If yes, remove prefix and return. If no, still return the code.
codeList1 = "abc,pqr,100101,101001,108972";
or
codeList2 = "mno, 100101,108972";
As you can see, I can get codes (P101001 or 101001) and (R108972 ,108972) format. There is will be only one prefix only.
If I am getting(P101001), I want to remove 'P' prefix and return number 101001.
If I am getting 101001, do nothing.
Below is the working code. But is there any easier or more efficient way of achieving this. Please help
for (String code : codeList.split(",")) {
if(StringUtils.isNumeric(code)) {
codes.add(code);
} else if(StringUtils.isNumeric(code.substring(1))) {
codes.add(Integer.toString(Integer.parseInt(code.substring(1))));
} else {
codes.add(code);
}
}
If you want to remove prefixes from the numbers you can easilly use :
String[] codes = {"abc,pqr,100101,P101001,R108972", "mno, 100101,108972"};
for (String code : codes){
System.out.println(
code.replaceAll("\\b[A-Z](\\d+)\\b", "$1")
);
}
Outputs
abc,pqr,100101,101001,108972
mno, 100101,108972
If you are using Java 8+, and want to extract only the numbers, you can just use :
String codeList1 = "abc,pqr,100101,P101001,R108972";
List<Integer> results = Arrays.stream(codeList1.split("\\D")) //split with non degits
.filter(c -> !c.isEmpty()) //get only non empty results
.map(Integer::valueOf) //convert string to Integer
.collect(Collectors.toList()); //collect to results to list
Outputs
100101
101001
108972
You can use regex to do it
String str = "abc,pqr,100101,P101001,R108972";
String regex = ",?[a-zA-Z]{0,}(\\d+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(matcher.group(1));
}
Output
100101
101001
108972
Updated:
For your comment(I want to add add the codes. If single alphabet prefix found , remove it and add remaining ),you can use below code:
String str = "abc,pqr,100101,P101001,R108972";
String regex = "(?=,?)[a-zA-Z]{0,}(?=\\d+)|\\s";// \\s is used to remove space
String[] strs = str.replaceAll(regex,"").split(",");
Output:
abc
pqr
100101
101001
108972
How about this:
String codeList1 = "abc,pqr,100101,P101001,R108972";
String[] codes = codeList1.split(",");
for (String code : codes) {
if (code.matches("[A-Z]?\\d{6}")) {
String codeF = code.replaceAll("[A-Z]+", "");
System.out.println(codeF);
}
}
100101
101001
108972
Demo
I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched
I am trying to parse the string with semicolon with multiple substrings, here are the example
String temp = "SIM1_TM_4G3G2G_DE;ANY_RAT;TCNAME_Flight_Mode_Toggle;TIME_60;120;90;30"
Expected output required would be to display only values after the TIME_:
60
120
90
30
I have tried with the following code it did not do the following need
String[] args_val=temp.split(";");
log("STARTING THE LOOP");
for(int ix=0; ix<args_val.length;ix++)
{
log("args_val["+ix+"]-" +args_val[ix]);
//TIME is considered in seconds
if(args_val[ix].contains(TIME"))
{
log("args_val[ix] length -" +args_val[ix].length());
String sTime = args_val[ix].substring(args_val[ix].indexOf("TIME_") +5, args_val[ix].length());
log("print sTime-" +sTime);
}
}
Try this:
String output = temp.substring(temp.indexOf("TIME_") + 5)
.replaceAll(";", "");
You may remove all the substring from start till and including ;TIME_ with the .*;TIME_ regex (note that the .* is a greedy dot matching pattern and will match from the start of the string till the last ;TIME_ on the line), and then split the rest with ;:
String temp = "SIM1_TM_4G3G2G_DE;ANY_RAT;TCNAME_Flight_Mode_Toggle;TIME_60;120;90;30";
String[] res = temp.replaceFirst(".*;TIME_", "").split(";");
System.out.println(res[0]);
System.out.println(res[1]);
System.out.println(res[2]);
System.out.println(res[3]);
See the Java demo
This will work if the string you mention is always in this format.
I want split my string using regex.
String Str = " Dřevo5068Hlína5064Železo5064Obilí4895";
String reg = "(\\D+)(\\d+)(\\D+)(\\d+)(\\D+)(\\d+)(\\D+)(\\d+)";
if (Str.matches(reg)) {
String[] l = Str.split(reg);
System.out.println(Arrays.toString(l));
}
But, output is []. Where is problem?
Edit: I want split to:
Dřevo
5068
Hlína
5064
Železo
5064
Obilí
4895
Then I want get numbers from this String.
if your engine permits look-around, split using this pattern
(?<=\D)(?=\d)|(?<=\d)(?=\D)
Demo
With this string "ADACADABRA". how to extract "CADA" From string "ADACADABRA" in java.
and also how to extract the id between "/" and "?" from the link below.
http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0
output should be: zaaU9lJ34c5
but should use "/" and "?" in the process.
and also how to extract the id between "/" and "?" from the link below.
http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0
output should be: zaaU9lJ34c5
Should be :
String url = "http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0";
String str = url.substring(url.lastIndexOf("/") + 1, url.indexOf("?"));
String s = "ADACADABRA";
String s2 = s.substring(3,7);
Here 3 specifies the beginning index, and 7 specifies the stopping point.
The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
I'm not entirely sure what you mean by extract, so I've provided the code to remove it from the String, I'm not certain if this is what you want.
public static void main (String args[]){
String string = "ADACADABRA";
string = string.replace("CADA", "");
System.out.println(string);
}
This is untested but something like this may help for the youtube part:
String youtubeUrl = "http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0";
String[] urlParts = youtubeUrl.split("/");
String videoId = urlParts[urlParts.length - 1];
videoId = videoId.substring(0, videoId.indexOf("?"));
Extracting CADA from the string makes no sense. You will need to specify how you have determined that CADA is the string to extract.
E.g. is it because it is the middle 4 characters? Is it because you are stripping off 3 characters each side? Are you just looking for the String "CADA"? Is it characters 3,7 of the String? Is it the first 4 of the last 7 characters of a String? Is it because it contains 2 vowels and 2 consanants? I could go on..
String regex = "CADA";
Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
Matcher m = p.matcher(originalText);
while (m.find()) {
String outputThis = m.group(1);
}
Use this tool http://www.regexplanet.com/advanced/java/index.html
Probably, you don't take in account the fact of java.lang.String immutability. That's why you need to assign the result of substringing to a new variable.