string manipulation in Java for extracting - java

I have a string like delivery:("D1_0"), how do i get the value inside the quotes alone from it. i.e D1_0 alone from it.

You could use regualr expresion like \"(.*?)\" to find that group, or even better, iterate over your String looking for quote marks " and reading characters inside of them until you find another quote mark. Something similar to this.

Try this
int i = stringvariable.indexOf("(");
int j = stringvariable.indexOf(")");
String output = stringvariable.substring(i+2, j-2);
You will get the required value in output variable.

If your string is constant, in that the beginning of the string will not change, you could use the slice function
In Javascript:
var text='delivery:("D1_0")';
alert(text.slice(11, 15)); //returns "D1_0"
In Java:
String text = "delivery:(\"D1_0\")";
String extract = text.substring(11, 15);

Use:
String str = "delivery:(\"D1_0\")";
String arr[] = str.split("[:\"()]"); //you will get arr[delivery, , , D1_0], choose arr[3]
System.out.println(arr[3]);

"If your String is always in this format you can use
String theString = "delivery:(\"D1_0\")";
String array[] = theString.split("\"");
String result = array[1]; // now result string is D1_0
// Note: array[0] contains the first part(i.e "delivery:(" )
// and array[2] contains the second (i.e ")" )

Related

I need Split String in java?

I have String like String str = "Abhishek Patel(123121)"; Nd I want Split String in two part.
String Name = "Abhishek Patel";
String ID = 123121;
i had tried like this in in java
String str = "Abhishek Patel(123121)";
String a[] = str.split("(");
String Name =a[0];
You can use a combination of split and substring
String name = "Abhishek Patel(1234567)";
String[] parts = name.split("\\(");
System.out.println(parts[0]);
System.out.println(parts[1].substring(0, parts[1].length() -1));
As #JoakimDanielson has correctly pointed out, if the last ) is optional then it maybe be better to use replace rather than substring
System.out.println(parts[1].replace(")", ""));
Take advantage of two facts.
The split method by default throws away any empty strings that appear after the matches.
You don't need to escape ( or ) if they appear in [] characters in a regular expression.
So you can just write this.
String toSplit = "Abishek Patel(12345)";
String[] parts = toSplit.split("[()]");
This gives an array of only two elements, not three, and they are the name and id.
Try this. will help you
String str = "Abhishek Patel(123121)";
String a[] = str.replace("(", " ").replace(")", " ").split(" ");
String Name =a[0];
String id =a[1];
System.out.println(Name);
System.out.println(id);
EDIT-------------
as suggested by Scary Wombat that there could be 2 spaces in the name it self. You can change this to something else.
The basic idea was to remove the unwanted and boundry characters with one common and split then.
Thanks #ScaryWombat.

Replacing all subsequent characters of a string, after matching a substring

I try to replace a character and all it's following characters within a string with another character.
This is my code so far.
String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)
the result should be: "Petabc"
I would highly appreciate any help on this matter!
A way to achive your goal:
search the string for the first appearance of the sequnce you want to replace
use that index and cut the string using String#substring
add your replace sequence to the end of the substring you just created
fin.
Good luck.
EDIT
In code it might look like this (not tested)
public static String customReplace(String input, String replace)
{
int index = input.indexOf(replace);
if(index >= 0)
{
return input.substring(index) + replace; //cutting string down to the required part and adding the replace
}
else
return null; //String 'input' doesn't contain String 'replace'
}
You could use a Regular Expression here with String's built-in replaceAll method to very easily do what you want:
original.replaceFirst(toReplace + ".*", replaceWith);
For example:
String original = "testing 123";
String toReplace = "ing";
String replaceWith = "er";
String replaced = original.replaceFirst(toReplace + ".*", replaceWith);
After the above, replaced will be set to "tester".

how to get the substring

i have a string sssssh and i want to get the result as h only. it only can solve while i have another string ssssth and i will get th also without the s in front. whether i need to split it? can anyone help me?
i don't want to use - to separate by inserting the split coding since my string is like this.
before this i originally the string is h then i using String.format to insert ssss in front of the h. lastly i need to remove all the s and get the original string h.
String str1 = ssssh;
String result = h;
You could use the String method to get the index of the last character 's':
int lastOccurenceOfS = str1.lastIndexOf("s");
Then you split your string from the next character forward:
String endString = str1.subString(lastOccurenceOfS + 1);
If what your asking is to split the h from all the other characters you can use this:
String str1 = "ssssh";
char ch = str1.charAt(str1.length() - 1);
Then what you are left with is the Char ch(h)

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.

Best way to parse this string in java?

I have a string that is the form of:
{'var1':var2}
I was able to parse this string so that var1 and var2 are both string variables. However it takes multiple string tokenizer calls, first to split from the ":" and then to extract the data.
So what would be the best (least lines of code) to do this?
If you just want an array containing the two values, then you can can do it in two lines by extracting a substring and then splitting on "':". It would end up looking something like this:
s = s.substring(2, s.length()-1);
String[] sarr = s.split("':");
If you really wanted a single line of code, you could combine them into:
String[] sarr = s.substring(2, s.length()-1).split("':");
This is unsolvable in the general case.
Consider for example:
case a)
var1=
:':':
var2=
':'
The the full original string would be
{':':':':':'}
case b)
var1=
:
var2=
':':':'
the the full original string would be
{':':':':':'}
So, we need "more information". Depending on your requirements / use case you had to live with the ambiguity, put limitations on the strings, or escape/encode the strings.
This should work:
String yourstring = "{'var1':var2}";
String regex = "\\{'(.+)':(.+)}";
Matcher m = Pattern.compile(regex).matcher(yourstring);
String var1 = m.group(1);
String var2 = m.group(2);
EDIT: for the commentators:
String:
{'this is':somestring':more stuff:for you}
Output:
var1 = this is':somestring
var2 = more stuff:for you
PS: tested with Perl, don't have Java at hand right now, sorry.
EDIT: looks like Java regex engine does not like { unescaped as user unknown points out. Escaped it.
Something like (fragile - see comment(s)):
// 3 lines..
String[] parts = "{'var1':var2} ".trim().split("':");
String var1 = parts[0].substring(2,parts[0].length);
String var2 = parts[1].substring(0,parts[1].length-1);
You can use regex:
String re = "\\{'(.*)':(.*)}";
String var1 = s.replaceAll (re, "$1");
String var2 = s.replaceAll (re, "$2");
You need to mask the opening {, else you get an java.util.regex.PatternSyntaxException: Illegal repetition

Categories