java how to split string from end - java

I have a string like "test.test.test"...".test" and i need to access last "test" word in this string. Note that the number of "test" in the string is unlimited. if java had a method like php explode function, everything was right, but... . I think splitting from end of string, can solve my problem.
Is there any way to specify direction for split method?
I know one solution for this problem can be like this:
String parts[] = fileName.split(".");
//for all parts, while a parts contain "." character, split a part...
but i think this bad solution.

Try substring with lastIndexOf method of String:
String str = "almas.test.tst";
System.out.println(str.substring(str.lastIndexOf(".") + 1));
Output:
tst

I think you can use lastIndexOf(String str) method for this purpose.
String str = "test.test.test....test";
int pos = str.lastIndexOf("test");
String result = str.substring(pos);

Related

Split a string based on pattern and merge it back

I need to split a string based on a pattern and again i need to merge it back on a portion of string.
for ex: Below is the actual and expected strings.
String actualstr="abc.def.ghi.jkl.mno";
String expectedstr="abc.mno";
When i use below, i can store in a Array and iterate over to get it back. Is there anyway it can be done simple and efficient than below.
String[] splited = actualstr.split("[\\.\\.\\.\\.\\.\\s]+");
Though i can acess the string based on index, is there any other way to do this easily. Please advise.
You do not understand how regexes work.
Here is your regex without the escapes: [\.\.\.\.\.\s]+
You have a character class ([]). Which means there is no reason to have more than one . in it. You also don't need to escape .s in a char class.
Here is an equivalent regex to your regex: [.\s]+. As a Java String that's: "[.\\s]+".
You can do .split("regex") on your string to get an array. It's very simple to get a solution from that point.
I would use a replaceAll in this case
String actualstr="abc.def.ghi.jkl.mno";
String str = actualstr.replaceAll("\\..*\\.", ".");
This will replace everything with the first and last . with a .
You could also use split
String[] parts = actualString.split("\\.");
string str = parts[0]+"."+parts[parts.length-1]; // first and last word
public static String merge(String string, String delimiter, int... partnumbers)
{
String[] parts = string.split(delimiter);
String result = "";
for ( int x = 0 ; x < partnumbers.length ; x ++ )
{
result += result.length() > 0 ? delimiter.replaceAll("\\\\","") : "";
result += parts[partnumbers[x]];
}
return result;
}
and then use it like:
merge("abc.def.ghi.jkl.mno", "\\.", 0, 4);
I would do it this way
Pattern pattern = Pattern.compile("(\\w*\\.).*\\.(\\w*)");
Matcher matcher = pattern.matcher("abc.def.ghi.jkl.mno");
if (matcher.matches()) {
System.out.println(matcher.group(1) + matcher.group(2));
}
If you can cache the result of
Pattern.compile("(\\w*\\.).*\\.(\\w*)")
and reuse "pattern" all over again this code will be very efficient as pattern compilation is the most expensive. java.lang.String.split() method that other answers suggest uses same Pattern.compile() internally if the pattern length is greater then 1. Meaning that it will do this expensive operation of Pattern compilation on each invocation of the method. See java.util.regex - importance of Pattern.compile()?. So it is much better to have the Pattern compiled and cached and reused.
matcher.group(1) refers to the first group of () which is "(\w*\.)"
matcher.group(2) refers to the second one which is "(\w*)"
even though we don't use it here but just to note that group(0) is the match for the whole regex.

Replace character with a particular String in Java

I have a program which should replace a alternate characters in the string with a new string. Lets say I have...
String s1 = "JAVAJAVA";
String s2 = "VA";
Output:
VAAVAAVAAVAA
Character in the each alternate index of s1 should be replaced with s2. I've tried using StringBulider but I'm not able to proceed further with it. Can someone help me out on this please. thanks
Try this:
s1 = s1.replaceAll(".(.)", s2+"$1");
Explanation: Regular Expression ".(.)" matches every 2 characters. The second char is "remembered" (brackets), so you can re-use it in the replacement part ($1):
If you want to go other way than REGEX other simple solution can be, though regex one should be preferred one
1) Split String to char array with String class toCharArray() function
2) Replace the new character at alternate position by running loop
3) Convert back array to string with new String(charArray)
have you tried string replace function?
here are some examples: http://javarevisited.blogspot.ch/2011/12/java-string-replace-example-tutorial.html
You can use it like this:
String newString = s1.replace("J", s2);

Splitting string into substring in Java

I have one string and I want to split it into substring in Java, originally the string is like this
Node( <http://www.mooney.net/geo#wisconsin> )
Now I want to split it into substring by (#), and this is my code for doing it
String[] split = row.split("#");
String word = split[1].trim().substring(0, (split[1].length() -1));
Now this code is working but it gives me
"wisconsin>"
the last work what I want is just the work "wisconsin" without ">" this sign, if someone have an idea please help me, thanks in advance.
Java1.7 DOC for String class
Actually it gives you output as "wisconsin> " (include space)
Make subString() as
String word = split[1].trim().substring(0, (split[1].length()-3));
Then you will get output as
wisconsin
Tutorials Point String subString() method reference
Consider
String split[] = row.split("#|<|>");
which delivers a String array like this,
{"http://www.mooney.net/geo", "wisconsin"}
Get the last element, at index split.length()-1.
String string = "Enter parts here";
String[] parts = string.split("-");
String part1 = parts[0];
String part2 = parts[1];
you can just split like you did before once more (with > instead of #) and use the element [0] istead of [1]
You can just use replace like.
word.replace(char oldChar, char newChar)
Hope that helps
You can use Java String Class's subString() method.
Refer to this link.

How to get specific string out of long string

I have the following String (it is variable, but classpath is always the same):
C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler
and I want to get just
de.test.class.mho.communication.InterfaceXmlHandler
out of this string. The end
InterfaceXmlHandler
is variable, also the beginning before 'de' and the path itself is variable too, but
de.test.class.mho.
isn't variable.
Why not just use
String result = str.substring(str.lastIndexOf("de.test.class.mho."));
Instead of splitting you could get rid of the beginning of the string:
String input = "C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler";
String output = input.replaceAll(".*(de\\.test\\.class\\.mho.*)", "$1");
You can create a string-array with String.split("de.test.class.mho."). The Array will contain two Strings, the second String will be what you want.
String longString = ""; //whatever
String[] urlArr = longString.split("de.test.class.mho.");
String result;
if(urlArr.length > 1) {
result = "de.test.class.mho." urlArr[1]; //de.test.class.mho.whatever.whatever.whatever
}
You can use replaceAll() to "extract" the part you want:
String part = str.replaceAll(".*(?=de\\.test\\.class\\.mho\\.)", "");
This uses a look-ahead to find all characters before the target, and replace them with a blank (ie delete them).
You could quite reasonably ignore escaping the dots for brevity:
String part = str.replaceAll(".*(?=de.test.class.mho.)", "");
I doubt it would give a different result.

Java how can remove everything between two substring in a string

I want to remove any substring(s) in a string that begins with 'galery' and ends with 'jssdk));'
For instance, consider the following string:
Galery something something.... jssdk));
I need an algorithm that removes 'something something....' and returns 'Galery jssdk));'
This is what I've done, but it does not work.
newsValues[1].replaceAll("Galery.*?jssdK));", "");
Could probably be improved, I've done it fast:
public static String replaceMatching(String input, String lowerBound, String upperBound{
Pattern p = Pattern.compile(".*?"+lowerBound+"(.*?)"+upperBound+".*?");
Matcher m = p.matcher(input);
String textToRemove = "";
while(m.find()){
textToRemove = m.group(1);
}
return input.replace(textToRemove, "");
}
UPDATE Thx for accepting the answer, but here is a smaller reviewed version:
public static String replaceMatching2(String input, String lowerBound, String upperBound){
String result = input.replaceAll("(.*?"+lowerBound + ")" + "(.*?)" + "(" + upperBound + ".*)", "$1$3");
return result;
}
The idea is pretty simple actually, split the String into 3 groups, and replace those 3 groups with the first and third, droping the second one.
You are almost there, but that will remove the entire string. If you want to remove anything between Galery and jssdK));, you will have to do something like so:
String newStr = newsValues[1].replaceAll("(Galery)(.*?)(jssdK\\)\\);)","$1$3");
This will put the strings into groups and will then use these groups to replace the entire string. Note that in regex syntax, the ) is a special character so it needs to be escaped.
String str = "GaleryABCDEFGjssdK));";
String newStr = str.replaceAll("(Galery)(.*?)(jssdK\\)\\);)","$1$3");
System.out.println(newStr);
This yields: GaleryjssdK));
I know that the solution presented by #amit is simpler, however, I thought it would be a good idea to show you a useful way in which you can use the replaceAll method.
Simplest solution will be to replace the string with just the "edges", effectively "removing" 1 everything between them.
newsValues[1].replaceAll("Galery.*?jssdK));", "GaleryjssdK));");
1: I used "" here because it is not exactly replacing - remember strings are immutable, so it is creating a new object, without the "removed" part.
newsValues[1] = newsValues[1].substring(0,6)+newsValues.substring(newsValues[1].length()-5,newsValues[1].length())
This basically concatenates the "Galery" and the "jssdk" leaving or ignoring everything else. More importantantly, you can simply assign newValues[1] = "Galeryjssdk"

Categories