I want to get an output first-second from the string below:
first-second-third
So basically what i want is to get the string before the last dash (-).
Can anyone give me a best solution for this?
Well, many down votes but I'll add a solution
the most efficient way to do that is using java.lang.String#lastIndexOf, which returns the index within this string of the last occurrence of the specified character, searching backwards
lastIndexOf will return -1 if dash does not exist
String str = "first-second-third";
int lastIndexOf = str.lastIndexOf('-');
System.out.println(lastIndexOf);
System.out.println(str.substring(0, lastIndexOf)); // 0 represent to cut from the beginning of the string
output:
12
first-second
String s = "first-second-third";
String newString = s.substring(0,s.lastIndexOf("-"));
Just an another way other than lastIndex method, using regex too can be done, try below code:
Pattern p = Pattern.compile("\\s*(.*)-.*");
Matcher m = p.matcher("first-second-third");
if (m.find())
System.out.println(m.group(1));
Related
I am far from mastering regular expressions but I would like to split a string on first and last underscore e.g.
split the string on first and last underscore with regular expression
"hello_5_9_2018_world"
to
"hello"
"5_9_2018"
"world"
I can split it on the last underscore with
String[] splitArray = subjectString.split("_(?=[^_]*$)");
but I am not able to figure out how to split on first underscore.
Could anyone show me how I can do this?
Thanks
David
You can achieve this without regex. You can achieve this by finding the first and last index of _ and getting substrings based on them.
String s = "hello_5_9_2018_world";
int firstIndex = s.indexOf("_");
int lastIndex = s.lastIndexOf("_");
System.out.println(s.substring(0, firstIndex));
System.out.println(s.substring(firstIndex + 1, lastIndex));
System.out.println(s.substring(lastIndex + 1));
The above prints
hello
5_9_2018
world
Note:
If the string does not have two _ you will get a StringIndexOutOfBoundsException.
To safeguard against it, you can check if the extracted indices are valid.
If firstIndex == lastIndex == -1 then it means the string does
not have any underscores.
If firstIndex == lastIndex then the string has just one underscore.
If you have always three parts as above, you can use
([^_]*)_(.*)_(^_)*
and get the single elements as groups.
Regular Expression
(?<first>[^_]+)_(?<middle>.+)+_(?<last>[^_]+)
Demo
Java Code
final String str = "hello_5_9_2018_world";
Pattern pattern = Pattern.compile("(?<first>[^_]+)_(?<middle>.+)+_(?<last>[^_]+)");
Matcher matcher = pattern.matcher(str);
if(matcher.matches()) {
String first = matcher.group("first");
String middle = matcher.group("middle");
String last = matcher.group("last");
}
I see that a lot of guys provided their solution, but I have another regex pattern for your question
You can achieve your goal with this pattern:
"([a-zA-Z]+)_(.*)_([a-zA-Z]+)"
The whole code looks like this:
String subjectString= "hello_5_9_2018_world";
Pattern pattern = Pattern.compile("([a-zA-Z]+)_(.*)_([a-zA-Z]+)");
Matcher matcher = pattern.matcher(subjectString);
if(matcher.matches()){
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
}
It outputs:
hello
5_9_2018
world
While the other answers are actually nicer and better, if you really want to use split, this is the way to go:
"hello_5_9_2018_world".split("((?<=^[^_]*)_)|(_(?=[^_]*$))")
==> String[3] { "hello", "5_9_2018", "world" }
This is a combination of your lookahead pattern (_(?=[^_]*$))
and the symmetrical look-behind pattern: ((?<=^[^_]*)_)
(match the _ preceeded by ^ (start of the string) and [^_]* (0..n non-underscore chars).
I am currently having an annoying issue. I would like to find an index of the very first integer value inside a string in order to cut the string next.
String currentPlayerInfo = "97 Dame Zeraphine [TBC] 10 41.458 481 363 117";
String currentPlayerName = "Dame Zeraphine [TBC]"; // This ís a kind of output i would like to get from the string above
I have tried different solutions but I was not able to find a proper one in the end. I would be really glad if I could get some help.
If you are willing to use regular expressions, you can use pattern ^[\d\s]+(.*?)\s+\d.
This will skip all numbers and spaces in beginning of String, and take everything up to a number of spaces followed by a digit.
This will only work if the playerName does not contain a digit (preceded by a space).
String currentPlayerInfo = "97 Dame Zeraphine [TBC] 10 41.458 481 363 117";
Pattern pattern = Pattern.compile("^[\\d\\s]+(.*?)\\s+\\d");
Matcher matcher = pattern.matcher(currentPlayerInfo);
String currentPlayerName;
if (matcher.find()) {
currentPlayerName = matcher.group(1);
} else {
currentPlayerName = null;
}
You can replace all numbers from your input to get that result, so you can use replaceAll with this regex \d+(\.\d+)? :
currentPlayerInfo = currentPlayerInfo.replaceAll("\\d+(\\.\\d+)?", "").trim();
Output
Dame Zeraphine [TBC]
So I have Strings 22test12344DC and 1name23234343dc
I want the best way to extract the first found full int from a String.
So this would return 22 and 1 from the above examples. The first full int's found
I tried this way, but I don't want any values after the first char.
mystr.split("[a-z]")[0]
Try this.
String s = "22test12344DC";
String firstInt = s.replaceFirst(".*?(\\d+).*", "$1");
System.out.println(firstInt);
result:
22
Using regex and the right pattern will do the trick:
here is one example
Pattern.compile("\\d+|\\D+")
then break the while loop since you need only the 1st match
String myCodeString = "22test12344DC";
myCodeString = "1name23234343dc";
Matcher matcher = Pattern.compile("\\d+|\\D+").matcher(myCodeString);
while (matcher.find()) {
System.out.println(matcher.group());
break;
}
I have a string :
"id=40114662&mode=Edit&reminderId=44195234"
All i want from this string is the final number 44195234. I can't use :
String reminderIdFin = reminderId.substring(reminderId.lastIndexOf("reminderId=")+1);
as i cant have the = sign as the point it splits the string. Is there any other way ?
Try String.split(),
reminderIdFin.split("=")[3];
You can use indexOf() method to get where this part starts:
int index = reminderIdFin.indexOf("Id=") + 3;
the plus 3 will make it so that it jumps over these characters. Then you can use substring to pull out your wanted string:
String newString = reminderIdFin.substring(index);
Remove everything else and you'll be left with your target content:
String reminderIdFin = reminderId.replaceAll(".*=", "");
The regex matches everything up to the last = (the .* is "greedy").
I have a string Till No. S59997-RSS01 Now I need to extract the 01 from it , but the issue is that it is dynameic means
String TillNo =pinpadTillStore.getHwIdentifier();
The value S59997-RSS01 is in TillNo, that I come to know from debugging but in real time which value is coming inside TillNo , will not be known to me but the pattern of the value will be the same (S59997-RSS01) , Please advise how to extract the last two digits like(01)
int size = tillNo.length();
String value = tillNo.substring(size-2); // do this if size > 2.
You can use the subString method.
Refer to how to use subString()
If the two digits will only appear at last two position, just use the substring method. For a more flexible way, use Regular Expression instead.
String TillNo = "S59997-RSS01";
System.out.println(TillNo.substring(TillNo.length() - 2));
Pattern pattern = Pattern.compile("S[\\d]{5}-RSS([\\d]{2})");
Matcher matcher = pattern.matcher(TillNo);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
exactly, you can extract the last 2 digits using the substring method for strings like:
String TillNo="S59997-RSS01";
String substring=TillNo.substring(TillNo.length()-2,TillNo.length());