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;
}
Related
I want a dynamic code which will trim of some part of the String at the beginning and some part at last. I am able to trim the last part but not able to trim the initial part of the String to a specific point completely. Only the first character is deleted in the output.
public static String removeTextAndLastBracketFromString(String string) {
StringBuilder str = new StringBuilder(string);
int i=0;
do {
str.deleteCharAt(i);
i++;
} while(string.equals("("));
str.deleteCharAt(string.length() - 2);
return str.toString();
}
This is my code. When I pass Awaiting Research(5056) as an argument, the output given is waiting Research(5056. I want to trim the initial part of such string till ( and I want only the digits as my output. My expected output here is - 5056. Please help.
You don't need loops (in your code), you can use String.substring(int, int) in combination with String.indexOf(char):
public static void main(String[] args) {
// example input
String input = "Awaiting Research(5056)";
// find the braces and use their indexes to get the content
String output = input.substring(
input.indexOf('(') + 1, // index is exclusive, so add 1
input.indexOf(')')
);
// print the result
System.out.println(output);
}
Output:
5056
Hint:
Only use this if you are sure the input will always contain a ( and a ) with indexOf('(') < indexOf(')') or handle IndexOutOfBoundsExceptions, which will occur on most Strings not matching the braces constraint.
If your goal is just to look one numeric value of the string, try split the string with regex for the respective numeric value and then you'll have the number separated from the string
e.g:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("somestringwithnumberlike123");
if(matcher.find()) {
System.out.println(matcher.group());
}
Using a regexp to extract what you need is a better option :
String test = "Awaiting Research(5056)";
Pattern p = Pattern.compile("([0-9]+)");
Matcher m = p.matcher(test);
if (m.find()) {
System.out.println(m.group());
}
For your case, battery use regular expression to extract your interested part.
Pattern pattern = Pattern.compile("(?<=\\().*(?=\\))");
Matcher matcher = pattern.matcher("Awaiting Research(5056)");
if(matcher.find())
{
return matcher.group();
}
It is much easier to solve the problem e.g. using the String.indexOf(..) and String.substring(from,to). But if, for some reason you want to stick to your approach, here are some hints:
Your code does what is does because:
string.equals("(") is only true if the given string is exacly "("
the do {code} while (condition)-loop executes code once if condition is not true -> think about using the while (condition) {code} loop instead
if you change the condition to check for the character at i, your code would remove the first, third, fifth and so on: After first execution i is 1 and char at i is now the third char of the original string (because the first has been removed already) -> think about always checking and removing charAt 0.
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]
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));
I've found something which almost fit my needs here
Integer.parseInt(s.replaceAll("[\\D]", ""))
but I can't find out how should I modify this to get negative integer. Sample string is:
"some\\-2c.st"
and I need to extract "-2"
I'd do it the other way around, look for the integer instead of stripping the rest:
String str = "some\\-2c.st";
Pattern pattern = Pattern.compile("-?[0-9]+");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
int value = Integer.parseInt(matcher.group());
System.out.println(value);
}
Integer.parseInt(s.replaceAll("[^\\d-]", ""))
You can remove everything you don't want, or you can extract that what you want.
It seems, the latter is more appropriate here, you can use a regex like (-?\d+) to do it.
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());