Regarding extracting a string - java

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());

Related

Java - Split string with multiple dash

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));

How to find a String of last 2 items in colon separated string

I have a string = ab:cd:ef:gh. On this input, I want to return the string ef:gh (third colon intact).
The string apple:orange:cat:dog should return cat:dog (there's always 4 items and 3 colons).
I could have a loop that counts colons and makes a string of characters after the second colon, but I was wondering if there exists some easier way to solve it.
You can use the split() method for your string.
String example = "ab:cd:ef:gh";
String[] parts = example.split(":");
System.out.println(parts[parts.length-2] + ":" + parts[parts.length-1]);
String example = "ab:cd:ef:gh";
String[] parts = example.split(":",3); // create at most 3 Array entries
System.out.println(parts[2]);
The split function might be what you're looking for here. Use the colon, like in the documentation as your delimiter. You can then obtain the last two indexes, like in an array.
Yes, there is easier way.
First, is by using method split from String class:
String txt= "ab:cd:ef:gh";
String[] arr = example.split(":");
System.out.println(arr[arr.length-2] + " " + arr[arr.length-1]);
and the second, is to use Matcher class.
Use overloaded version of lastIndexOf(), which takes the starting index as 2nd parameter:
str.substring(a.lastIndexOf(":", a.lastIndexOf(":") - 1) + 1)
Another solution would be using a Pattern to match your input, something like [^:]+:[^:]+$. Using a pattern would probably be easier to maintain as you can easily change it to handle for example other separators, without changing the rest of the method.
Using a pattern is also likely be more efficient than String.split() as the latter is also converting its parameter to a Pattern internally, but it does more than what you actually need.
This would give something like this:
String example = "ab:cd:ef:gh";
Pattern regex = Pattern.compile("[^:]+:[^:]+$");
final Matcher matcher = regex.matcher(example);
if (matcher.find()) {
// extract the matching group, which is what we are looking for
System.out.println(matcher.group()); // prints ef:gh
} else {
// handle invalid input
System.out.println("no match");
}
Note that you would typically extract regex as a reusable constant to avoid compiling the pattern every time. Using a constant would also make the pattern easier to change without looking at the actual code.

Filter and find integers in a String with Regex

I have this long string:
String responseData = "fker.phone.bash,0,0,0"
+ "fker.phone.bash,0,0,0"
+ "fker.phone.bash,2,0,0";
What I want to do is to extract the integers in this string. I have successfully done that with this code:
String pattern = "(\\d+)";
// this pattern finds EVERY integer. I only want the integers after the comma
Pattern pr = Pattern.compile(pattern);
Matcher match = pr.matcher(responseData);
while (match.find()) {
System.out.println(match.group());
}
So far it is working, but I want to make my regex more secure because the responsedata I get is dynamic. Sometimes I might get an integer in the middle of the string, but I only want the last integers, meaning after the comma.
I know the regex for starts with is ^ and I have to put my comma tecken as an argument, but I don't know how to piece it all together and that is why I am asking for help. Thank you.
String pattern = "(,)(\\d)+";
Then get the second group.
You can use positive lookbehind for that:
String pattern = "(?<=,)\\d+";
You don't need to extract any groups to do use that solution, because lookbehind is zero-length assertion.
You can simply use the following and find by match.group(1):
String pattern = ",(\\d+)";
See working demo
You can also use word boundaries to get independent numbers:
String pattern = "\\b(\\d+)\\b";

Why doesn't /0/g match in a string that contains zeroes?

This code always returns "false" at last, even if Integer contains any zero:
Integer i = (int) rand(1, 200); // random [1;200)
String regexp = "/0/g";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(i.toString());
print(i);
print(m.matches());
What is the reason? I don't get where the mistake could be.
Needed: m.matches() = "true" if Integer contains one or more zero.
The problem is that you're giving the regular expression incorrectly. The string you give Pattern.compile is just the text of the expression, without / on either side, and without flags; flags are specified separately.
So in your case, you'd just want:
String regexp = "0";
There's no "global" flag; instead, you use the methods on the resulting Matcher as appropriate to what you're doing.
Needed: m.matches() = "true" if Integer contains one or more zero.
Then you don't want to use Matcher#matches, you want Match#find. Or if you need to use Matcher#matches, the expression would be:
String regexp = ".*0.*";
...e.g., any number of any character, then a 0, then any number of any character. That way, the entire string can match the expression.
Of course, if you just want to know there's a zero, it's much simpler to just use
boolean flag = String.valueOf(i).indexOf('0') != -1;
In this particular case you don't need a regex at all since you are looking for a literal character, use indexOf:
if (Str.indexOf( '0' ) != -1) {
...
about your original pattern:
regex don't need to be enclosed between delimiters in Java, so slashes are useless. The global modifier isn't needed too because the global nature is determined by the method you choose. (in other words, the only way to obtain several results is to use the find method in a loop to obtain the different results)
print(m.find());
Matcher will match from beginning.Use find as 0 input is not possible in your case.
Using find will enable you to locate 0 anywhere in the string.
matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence false.
Also change your regex to "0" as suggested by the other answer.
Try,
String regexp = ".*0.*";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(i.toString());
if(m.find()){
System.out.println(i);
System.out.println(m.matches());
}
Regex :

Matching everything after the first comma in a string

I am using java to do a regular expression match. I am using rubular to verify the match and ideone to test my code.
I got a regex from this SO solution , and it matches the group as I want it to in rubular, but my implementation in java is not matching. When it prints 'value', it is printing the value of commaSeparatedString and not matcher.group(1) I want the captured group/output of println to be "v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso"
String commaSeparatedString = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso";
//match everything after first comma
String myRegex = ",(.*)";
Pattern pattern = Pattern.compile(myRegex);
Matcher matcher = pattern.matcher(commaSeparatedString);
String value = "";
if (matcher.matches())
value = matcher.group(1);
else
value = commaSeparatedString;
System.out.println(value);
(edit: I left out that commaSeparatedString will not always contain 2 commas. Rather, it will always contain 0 or more commas)
If you don't have to solve it with regex, you can try this:
int size = commaSeparatedString.length();
value = commaSeparatedString.substring(commaSeparatedString.indexOf(",")+1,size);
Namely, the code above returns the substring which starts from the first comma's index.
EDIT:
Sorry, I've omitted the simpler version. Thanks to one of the commentators, you can use this single line as well:
value = commaSeparatedString.substring( commaSeparatedString.indexOf(",") );
The definition of the regex is wrong. It should be:
String myRegex = "[^,]*,(.*)";
You are yet another victim of Java's misguided regex method naming.
.matches() automatically anchors the regex at the beginning and end (which is in total contradiction with the very definition of "regex matching"). The method you are looking for is .find().
However, for such a simple problem, it is better to go with #DelShekasteh's solution.
I would do this like
String commaSeparatedString = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso";
System.out.println(commaSeparatedString.substring(commaSeparatedString.indexOf(",")+1));
Here is another approach with limited split
String[] spl = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso".split(",", 2);
if (spl.length == 2)
System.out.println(spl[1]);
Byt IMHO Del's answer is best for your case.
I would use replaceFirst
String commaSeparatedString = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso";
System.out.println(commaSeparatedString.replaceFirst(".*?,", ""));
prints
v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso
or you could use the shorter but obtuse
System.out.println(commaSeparatedString.split(",", 2)[1]);

Categories

Resources