I'm using codingbat.com to get some java practice in. One of the String problems, 'withoutString' is as follows:
Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive).
You may assume that the remove string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
This problem can be found at: http://codingbat.com/prob/p192570
As you can see from the the dropbox-linked screenshot below, all of the runs pass except for three and a final one called "other tests." The thing is, even though they are marked as incorrect, my output matches exactly the expected output for the correct answer.
Here's a screenshot of my output:
And here's the code I'm using:
public String withoutString(String base, String remove) {
String result = "";
int i = 0;
for(; i < base.length()-remove.length();){
if(!(base.substring(i,i+remove.length()).equalsIgnoreCase(remove))){
result = result + base.substring(i,i+1);
i++;
}
else{
i = i + remove.length();
}
if(result.startsWith(" ")) result = result.substring(1);
if(result.endsWith(" ") && base.substring(i,i+1).equals(" ")) result = result.substring(0,result.length()-1);
}
if(base.length()-i <= remove.length() && !(base.substring(i).equalsIgnoreCase(remove))){
result = result + base.substring(i);
}
return result;
}
Your solution IS failing AND there is a display bug in coding bat.
The correct output should be:
withoutString("This is a FISH", "IS") -> "Th a FH"
Yours is:
withoutString("This is a FISH", "IS") -> "Th a FH"
Yours fails because it is removing spaces, but also, coding bat does not display the correct expected and run output string due to HTML removing extra spaces.
This recursive solution passes all tests:
public String withoutString(String base, String remove) {
int remIdx = base.toLowerCase().indexOf(remove.toLowerCase());
if (remIdx == -1)
return base;
return base.substring(0, remIdx ) +
withoutString(base.substring(remIdx + remove.length()) , remove);
}
Here is an example of an optimal iterative solution. It has more code than the recursive solution but is faster since far fewer function calls are made.
public String withoutString(String base, String remove) {
int remIdx = 0;
int remLen = remove.length();
remove = remove.toLowerCase();
while (true) {
remIdx = base.toLowerCase().indexOf(remove);
if (remIdx == -1)
break;
base = base.substring(0, remIdx) + base.substring(remIdx + remLen);
}
return base;
}
I just ran your code in an IDE. It compiles correctly and matches all tests shown on codingbat. There must be some bug with codingbat's test cases.
If you are curious, this problem can be solved with a single line of code:
public String withoutString(String base, String remove) {
return base.replaceAll("(?i)" + remove, ""); //String#replaceAll(String, String) with case insensitive regex.
}
Regex explaination:
The first argument taken by String#replaceAll(String, String) is what is known as a Regular Expression or "regex" for short.
Regex is a powerful tool to perform pattern matching within Strings. In this case, the regular expression being used is (assuming that remove is equal to IS):
(?i)IS
This particular expression has two parts: (?i) and IS.
IS matches the string "IS" exactly, nothing more, nothing less.
(?i) is simply a flag to tell the regex engine to ignore case.
With (?i)IS, all of: IS, Is, iS and is will be matched.
As an addition, this is (almost) equivalent to the regular expressions: (IS|Is|iS|is), (I|i)(S|s) and [Ii][Ss].
EDIT
Turns out that your output is not correct and is failing as expected. See: dansalmo's answer.
public String withoutString(String base, String remove) {
String temp = base.replaceAll(remove, "");
String temp2 = temp.replaceAll(remove.toLowerCase(), "");
return temp2.replaceAll(remove.toUpperCase(), "");
}
Please find below my solution
public String withoutString(String base, String remove) {
final int rLen=remove.length();
final int bLen=base.length();
String op="";
for(int i = 0; i < bLen;)
{
if(!(i + rLen > bLen) && base.substring(i, i + rLen).equalsIgnoreCase(remove))
{
i +=rLen;
continue;
}
op += base.substring(i, i + 1);
i++;
}
return op;
}
Something things go really weird on codingBat this is just one of them.
I am adding to a previous solution, but using a StringBuilder for better practice. Most credit goes to Anirudh.
public String withoutString(String base, String remove) {
//create a constant integer the size of remove.length();
final int rLen=remove.length();
//create a constant integer the size of base.length();
final int bLen=base.length();
//Create an empty string;
StringBuilder op = new StringBuilder();
//Create the for loop.
for(int i = 0; i < bLen;)
{
//if the remove string lenght we are looking for is not less than the base length
// and the base substring equals the remove string.
if(!(i + rLen > bLen) && base.substring(i, i + rLen).equalsIgnoreCase(remove))
{
//Increment by the remove length, and skip adding it to the string.
i +=rLen;
continue;
}
//else, we add the character at i to the string builder.
op.append(base.charAt(i));
//and increment by one.
i++;
}
//We return the string.
return op.toString();
}
Taylor's solution is the most efficient one, however I have another solution that is a naive one and it works.
public String withoutString(String base, String remove) {
String returnString = base;
while(returnString.toLowerCase().indexOf(remove.toLowerCase())!=-1){
int start = returnString.toLowerCase().indexOf(remove.toLowerCase());
int end = remove.length();
returnString = returnString.substring(0, start) + returnString.substring(start+end);
}
return returnString;
}
#Daemon
your code works. Thanks for the regex explanation. Though dansalmo pointed out that codingbat is displaying the intended output incorrectly, I through in some extra lines to your code to unnecessarily account for the double spaces with the following:
public String withoutString(String base, String remove){
String result = base.replaceAll("(?i)" + remove, "");
for(int i = 0; i < result.length()-1;){
if(result.substring(i,i+2).equals(" ")){
result = result.replace(result.substring(i,i+2), " ");
}
else i++;
}
if(result.startsWith(" ")) result = result.substring(1);
return result;
}
public String withoutString(String base, String remove){
return base.replace(remove,"");
}
Related
I have requirement that need to get all combinations of given Strings.
For example
I have a String of digits and some special charcters
String chars="0123456789##$%&";
String guessedPw="authentic";
So I want to get combinations like this
$authentic%4
authentic##
5&authentic
authentic8
How should I improve my method to get all combinations?
This is the code that I have written.
but it doesn't give me all combinations.
private static String combination(String prefix, String s, String pw, String md5Pw) {
String pwFound = "";
if (s.length() > 0) {
// System.out.println(prefix + s.charAt(0) + pw);
String tempPw1 = prefix + s.charAt(0) + pw;
System.out.println("pw1 : " + tempPw1);
if (md5(tempPw1).equals(md5Pw)) {
// String tempPw1;
pwFound = tempPw1;
return pwFound;
}
String tempPw2 = pw + prefix + s.charAt(0);
if (md5(tempPw2).equals(md5Pw)) {
// String tempPw1;
pwFound = tempPw2;
return pwFound;
}
pwFound = combination(prefix + s.charAt(0), s.substring(1), pw, md5Pw);
pwFound = combination(prefix, s.substring(1), pw, md5Pw);
}
return pwFound;
}
Just if you don't want write own algo, you can use google.
Try to search for: "Generate Permutations".
For example, on this link: Generate all combinations from multiple lists there is a algo which you can use it (but with list).
void GeneratePermutations(List<List<Character>> Lists, List<String> result, int depth, String current)
{
if(depth == Lists.size())
{
result.add(current);
return;
}
for(int i = 0; i < Lists.get(depth).size(); ++i)
{
GeneratePermutations(Lists, result, depth + 1, current + Lists.get(depth).get(i));
}
}
But sure, there are a lot of other ways.
If you want to code everything by your own then this is how you should approach your problem =>
Have a special character say ~ to denote guessedPw, and create another string say str = chars + "~".
Now first you need to look for all possible combinations of str, finding which will take exponential time , and then for each found combination, you should generate all it's permutation , which is again factorial time complex. And then in the final string , you should replace all the occurrence of '~' with guessedPw, and get the answer string.
Here you go for the link for generating permutations and combinations :
Link : http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
To find out combinations , you can use bit-masking if you have at max. 64 characters in the string , combinations from which you want to extract.
To make new combination, you can add one char as prefix or add one char as suffix. To avoid repeats, stop adding prefix when suffix exists
Pseudocode:
GenPass(CurrentString, boolAllowPrefix)
check CurrentString, return it if good result
check length limit, exit if too long
for c in Chars
if (boolAllowPrefix)
GenPass(Chars[i] + CurrentString, True)
GenPass(s + Chars[i], False)
Delphi implementation to check
procedure GenPass(s: string; bPrefix: Boolean);
var
i: integer;
begin
List.Add(s);
if Length(s) = MaxLen then
Exit;
if bPrefix then
for i := 1 to Length(Chars) do
GenPass(Chars[i] + s, True);
for i := 1 to Length(Chars) do
GenPass(s + Chars[i], False);
end;
So recently I got invited to this google foo.bar challenge and I believe the code runs the way it should be. To be precise what I need to find is the number of occurrences of "abc" in a String. When I verify my code with them, I pass 3/10 test cases. I'm starting to feel bad because I don't know what I am doing wrong. I have written the code which I will share with you guys. Also the string needs to be less than 200 characters. When I run this from their website, I pass 3 tests and fail 7. Basically 7 things need to be right.
The actual question:
Write a function called answer(s) that, given a non-empty string less
than 200 characters in length describing the sequence of M&Ms. returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers.
Example : Input : (string) s = "abccbaabccba"
output : (int) 2
Input: (string) s = "abcabcabcabc"
output : (int) 4
public static int answer(String s) {
int counter = 0;
int index;
String findWord ="ABC";
if(s!=null && s.length()<200){
s = s.toUpperCase();
while (s.contains(findWord))
{
index = s.indexOf(findWord);
s = s.substring(index + findWord.length(), s.length());
counter++;
}
}
return counter;
}
I see a couple of things in your code snippet:
1.
if(s.length()<200){
Why are you checking for the length to be lesser than 200? Is that a requirement? If not, you can skip checking the length.
2.
String findWord ="abc";
...
s.contains(findWord)
Can the test program be checking for upper case alphabets? Example: "ABC"? If so, you might need to consider changing your logic for the s.contains() line.
Update:
You should also consider putting a null check for the input string. This will ensure that the test cases will not fail for null inputs.
The logic of your code is well but on the other hand i found that you didn't check for if input string is empty or null.
I belief that google foo.bar wants to see the logic and the way of coding in a proper manner.
so don't be feel bad
I would go for a simpler approach
int beforeLen = s.length ();
String after = s.replace (findWord, "");
int afterLen = after.length ();
return (beforeLen - afterLen) / findWord.length ();
String pattern = "abc";
String line="<input text here>";
int i=0;
Pattern TokenPattern=Pattern.compile(pattern);
if(line!=null){
Matcher m=TokenPattern.matcher(line);
while(m.find()){
i++;
}}
System.out.println("No of occurences : "+ " "+i);
put declaration of index out before while block, isn't never good re-declare the same variable n time.
int index;
while (s.contains(findWord))
{
index = s.indexOf(findWord);
....
}
I hope this help
Update:
try to compact your code
public static int answer(String s) {
int counter = 0;
int index;
String findWord = "ABC";
if (s != null && s.length() < 200) {
s = s.toUpperCase();
while ((index = s.indexOf(findWord)) > -1) {
s = s.substring(index + findWord.length(), s.length());
counter++;
}
}
return counter;
}
Update:
The logic seems good to me, I'm still try to improve the performance, if you can try this
while ((index = s.indexOf(findWord, index)) > -1) {
//s = s.substring(index + findWord.length(), s.length());
index+=findWord.length();
counter++;
}
public static String removeLeadingZeroes(String value):
Given a valid, non-empty input, the method should return the input with all leading zeroes removed. Thus, if the input is “0003605”, the method should return “3605”. As a special case, when the input contains only zeroes (such as “000” or “0000000”), the method should return “0”
public class NumberSystemService {
/**
*
* Precondition: value is purely numeric
* #param value
* #return the value with leading zeroes removed.
* Should return "0" for input being "" or containing all zeroes
*/
public static String removeLeadingZeroes(String value) {
while (value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I don't know how to write codes for a string "0000".
If the string always contains a valid integer the return new Integer(value).toString(); is the easiest.
public static String removeLeadingZeroes(String value) {
return new Integer(value).toString();
}
Stop reinventing the wheel.
Almost no software development problem you ever encounter will be the first time it has been encountered;
instead,
it will only be the first time you encounter it.
Almost every utility method you will ever need has already been written by the Apache project and/or the guava project (or some similar that I have not encountered).
Read the Apache StringUtils JavaDoc page.
This utility is likely to already provide every string manipulation functionality you will ever need.
Some example code to solve your problem:
public String stripLeadingZeros(final String data)
{
final String strippedData;
strippedData = StringUtils.stripStart(data, "0");
return StringUtils.defaultString(strippedData, "0");
}
You could add a check on the string's length:
public static String removeLeadingZeroes(String value) {
while (value.length() > 1 && value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I would consider checking for that case first. Loop through the string character by character checking for a non "0" character. If you see a non "0" character use the process you have. If you don't, return "0". Here's how I would do it (untested, but close)
boolean allZero = true;
for (int i=0;i<value.length() && allZero;i++)
{
if (value.charAt(i)!='0')
allZero = false;
}
if (allZero)
return "0"
...The code you already have
private String trimLeadingZeroes(inputStringWithZeroes){
final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
return trimZeroes.toString();
}
You can use below replace function it will work on a string having both alphanumeric or numeric
s.replaceFirst("^0+(?!$)", "")
public String removeLeadingZeros(String digits) {
//String.format("%.0f", Double.parseDouble(digits)) //Alternate Solution
String regex = "^0+";
return digits.replaceAll(regex, "");
}
removeLeadingZeros("0123"); //Result -> 123
removeLeadingZeros("00000456"); //Result -> 456
removeLeadingZeros("000102030"); //Result -> 102030
Convert input to StringBuilder
Use deleteCharAt method to remove character from beginning till non-zero character is found
String trimZero(String str) {
StringBuilder strB = new StringBuilder(str);
int index = 0;
while (strB.length() > 0 && strB.charAt(index) == '0') {
strB.deleteCharAt(index);
}
return strB.toString();
}
You can use pattern matcher to check for strings with only zeros.
public static String removeLeadingZeroes(String value) {
if (Pattern.matches("[0]+", value)) {
return "0";
} else {
while (value.indexOf("0") == 0) {
value = value.substring(1);
}
return value;
}
}
You can try this:
1. If the numeric value of the string is 0 then return new String("0").
2. Else remove the zeros from the string and return the substring.
public static String removeLeadingZeroes(String str)
{
if(Double.parseDouble(str)==0)
return new String("0");
else
{
int i=0;
for(i=0; i<str.length(); i++)
{
if(str.charAt(i)!='0')
break;
}
return str.substring(i, str.length());
}
}
Use String.replaceAll(), like this:
public String replaceLeadingZeros(String s) {
s = s.replaceAll("^[0]+", "");
if (s.equals("")) {
return "0";
}
return s;
}
This will match all leading zeros (using regex ^[0]+) and replace them all with blanks. In the end if you're only left with a blank string, return "0" instead.
int n = 000012345;
n = Integer.valueOf(n + "", 10);
It is important to specify radix 10, else the integer is read as an octal literal and an incorrect value is returned.
public String removeLeadingZeros(String num) {
String res = num.replaceAll("^0+", "").trim();
return res.equals("")? "0" : res;
}
I have found the following to be the simplest and most reliable, as it works for both integers and floating-point numbers:
public static String removeNonRequiredLeadingZeros(final String str) {
return new BigDecimal(str).toPlainString();
}
You probably want to check the incoming string for null and blank, and also trim it to remove leading and trailing whitespace.
You can also get rid of trailing zeros by using:
public static String removeNonRequiredZeros(final String str) {
return new BigDecimal(str).stripTrailingZeros().toPlainString();
}
My goal is to change any form of the word "java" in a sentence to "JAVA".I've got everything done but my code won't read in mixed cases for example:JaVa, JAva,etc. I know I am suppose to use toUpperCase and toLowerCase or equalsIgnoreCase but I am not sure how to use it properly. I am not allowed to use replace or replace all, teacher wants substring method.
Scanner input=new Scanner(System.in);
System.out.println("Enter a sentence with words including java");
String sentence=input.nextLine();
String find="java";
String replace="JAVA";
String result="";
int n;
do{
n=sentence.indexOf(find);
if(n!=-1){
result =sentence.substring(0,n);
result=result +replace;
result = result + sentence.substring(n+find.length());
sentence=result;
}
}while(n!=-1);
System.out.println(sentence);
}
}
You can't do that using String.indexOf because it is case sensitive.
The simple solution is to use a regex with a case insensitive pattern; e.g.
Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(str).replaceAll(repl);
That also has the benefit of avoiding the messy string-bashing you are currently using to do the replacement.
In your example, your input string is also valid as a regex ... because it doesn't include any regex meta-characters. If it did, then the simple workaround is to use Pattern.quote(str) which will treat the meta-characters as literal matches.
It is also worth nothing that String.replaceAll(...) is a "convenience method" for doing a regex replace on a string, though you can't use it for your example because it does case sensitive matching.
For the record, here is a partial solution that does the job by string-bashing. #ben - this is presented for you to read and understand ... not to copy. It is deliberately uncommented to encourage you to read it carefully.
// WARNING ... UNTESTED CODE
String input = ...
String target = ...
String replacement = ...
String inputLc = input.lowerCase();
String targetLc = target.lowerCase();
int pos = 0;
int pos2;
while ((pos2 = inputLc.indexOf(targetLc, pos)) != -1) {
if (pos2 - pos > 0) {
result += input.substring(pos, pos2);
}
result += replacement;
pos = pos2 + target.length();
}
if (pos < input.length()) {
result += input.substring(pos);
}
It probably be more efficient to use a StringBuilder instead of a String for result.
you are allowed to use toUpperCase() ? try this one
Scanner input=new Scanner(System.in);
System.out.println("Enter a sentence with words including java");
String sentence=input.nextLine();
String find="java";
String replace="JAVA";
String result="";
result = sentence.toLowerCase();
result = result.replace(find,replace);
System.out.println(result);
}
reply with the result :))
Update : Based on
I've got everything done but my code won't read in mixed cases for
example:JaVa, JAva,etc.
you can use your code
Scanner input=new Scanner(System.in);
System.out.println("Enter a sentence with words including java");
String sentence=input.nextLine();
String find="java";
String replace="JAVA";
String result="";
int n;
do{
//for you to ignore(converts the sentence to lowercase) either lower or upper case in your sentence then do the nxt process
sentence = sentence.toLowerCase();
n=sentence.indexOf(find);
if(n!=-1){
result =sentence.substring(0,n);
result=result +replace;
result = result + sentence.substring(n+find.length());
sentence=result;
}
}while(n!=-1);
System.out.println(sentence);
}
Update 2 : I put toLowerCase Convertion outside the loop.
public static void main(String[] args){
String sentence = "Hello my name is JAva im a jaVa Man with a jAvA java Ice cream";
String find="java";
String replace="JAVA";
String result="";
int n;
//for you to ignore(converts the sentence to lowercase) either lower or upper case in your sentence then do the nxt process
sentence = sentence.toLowerCase();
System.out.println(sentence);
do{
n=sentence.indexOf(find);
if(n!=-1){
result =sentence.substring(0,n);
result=result +replace;
result = result + sentence.substring(n+find.length());
sentence=result;
}
}while(n!=-1);
System.out.println(sentence);
}
RESULT
hello my name is java im a java man with a java java ice cream
hello my name is JAVA im a JAVA man with a JAVA JAVA ice cream
A quick solution would be to remove your do/while loop entirely and just use a case-insensitive regex with String.replaceAll(), like:
sentence = sentence.replaceAll("(?i)java", "JAVA");
System.out.println(sentence);
Or, more general and according to your variable namings:
sentence = sentence.replaceAll("(?i)" + find, replace);
System.out.println(sentence);
Sample Program
EDIT:
Based on your comments, if you need to use the substring method, here is one way.
First, since String.indexOf does case-sensitive comparisons, you can write your own case-insensitive method, let's call it indexOfIgnoreCase(). This method would look something like:
// Find the index of the first occurrence of the String find within the String str, starting from start index
// Return -1 if no match is found
int indexOfIgnoreCase(String str, String find, int start) {
for(int i = start; i < str.length(); i++) {
if(str.substring(i, i + find.length()).equalsIgnoreCase(find)) {
return i;
}
}
return -1;
}
Then, you can use this method in the following manner.
You find the index of the word you need, then you add the portion of the String before this word (up to the found index) to the result, then you add the replaced version of the word you found, then you add the rest of the String after the found word.
Finally, you update the starting search index by the length of the found word.
String find = "java";
String replace = "JAVA";
int index = 0;
while(index + find.length() <= sentence.length()) {
index = indexOfIgnoreCase(sentence, find, index); // use the custom indexOf method here
if(index == -1) {
break;
}
sentence = sentence.substring(0, index) + // copy the string up to the found word
replace + // replace the found word
sentence.substring(index + find.length()); // copy the remaining part of the string
index += find.length();
}
System.out.println(sentence);
Sample Program
You could use a StringBuilder to make this more efficient since the + operator creates a new String on each concatenation. Read more here
Furthermore, you could combine the logic in the indexOfIgnoreCase and the rest of the code in a single method like:
String find = "java";
String replace = "JAVA";
StringBuilder sb = new StringBuilder();
int i = 0;
while(i + find.length() <= sentence.length()) {
// if found a match, add the replacement and update the index accordingly
if(sentence.substring(i, i + find.length()).equalsIgnoreCase(find)) {
sb.append(replace);
i += find.length();
}
// otherwise add the current character and update the index accordingly
else {
sb.append(sentence.charAt(i));
i++;
}
}
sb.append(sentence.substring(i)); // append the rest of the string
sentence = sb.toString();
System.out.println(sentence);
I have created an application to process log files but am having some bottle neck when the amount of files = ~20
The issue comes from a particular method which takes on average a second or so to complete roughly and as you can imagime this isn't practical when it needs to be done > 50 times
private String getIdFromLine(String line){
String[] values = line.split("\t");
String newLine = substringBetween(values[4], "Some String : ", "Value=");
String[] split = newLine.split(" ");
return split[1].substring(4, split[1].length());
}
private String substringBetween(String str, String open, String close) {
if (str == null || open == null || close == null) {
return null;
}
int start = str.indexOf(open);
if (start != -1) {
int end = str.indexOf(close, start + open.length());
if (end != -1) {
return str.substring(start + open.length(), end);
}
}
return null;
}
A line comes from the reading of a file which is very efficient so I don't feel a need to post that code unless someone asks.
Is there anyway to improve perofmrance of this at all?
Thanks for your time
A few things are likely problematic:
Whether or not you realized, you are using regular expressions. The argument to String.split() is a treated as a regex. Using String.indexOf() will almost certainly be a faster way to find the particular portion of the String that you want. As HRgiger points out, Guava's splitter is a good choice because it does just that.
You're allocating a bunch of stuff you don't need. Depending on how long your lines are, you could be creating a ton of extra Strings and String[]s that you don't need (and the garbage collecting them). Another reason to avoid String.split().
I also recommend using String.startsWith() and String.endsWith() rather that all of this stuff that you're doing with the indexOf() if only for the fact that it'd be easier to read.
I would try to use regular expressions.
One of the main problems in this code is the "split" method.
For example this one:
private String getIdFromLine3(String line) {
int t_index = -1;
for (int i = 0; i < 3; i++) {
t_index = line.indexOf("\t", t_index+1);
if (t_index == -1) return null;
}
//String[] values = line.split("\t");
String newLine = substringBetween(line.substring(t_index + 1), "Some String : ", "Value=");
// String[] split = newLine.split(" ");
int p_index = newLine.indexOf(" ");
if (p_index == -1) return null;
int p_index2 = newLine.indexOf(" ", p_index+1);
if (p_index2 == -1) return null;
String split = newLine.substring(p_index+1, p_index2);
// return split[1].substring(4, split[1].length());
return split.substring(4, split.length());
}
UPD: It could be 3 times faster.
I would recommend to use the VisualVM to find the bottle neck before oprimisation.
If you need performance in your application, you will need profiling anyways.
As optimisation i would make an custom loop to replace yours substringBetween method and get rid of multiple indexOf calls
Google guava splitter pretty fast as well.
Could you try the regex anyway and post results please just for comparison:
Pattern p = Pattern.compile("(Some String : )(.*?)(Value=)"); //remove first and last group if not needed (adjust m.group(x) to match
#Test
public void test2(){
String str = "Long java line with Some String : and some object with Value=154345 ";
System.out.println(substringBetween(str));
}
private String substringBetween(String str) {
Matcher m = p.matcher(str);
if(m.find(2)){
return m.group(2);
}else{
return null;
}
}
If this is faster find a regex that combines both functions