I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();
Related
I have a string test in which I can see VD1 and and VD2.
How can I extract the value of VD1 and VD2 and store it in string.
String test =
"DomainName=xyz.zzz.com
&ModifiedOn=03%2f17%2f2015
&VD1=MTMwMDE3MDQ%3d
&VD2=B67E48F6969E99A0BC2BEE0E240D2B5C
&SiteLanguage=English"
Here value of VD1=MTMwMDE3MDQ%3d and VD2=B67E48F6969E99A0BC2BEE0E240D2B5C. But these are the dynamic values. Here VD1 and VD2 are seperated by '&'.
Try regex like this :
public static void main(String[] args) throws Exception {
String test = "DomainName=xyz.zzz.com&ModifiedOn=03%2f17%2f2015&VD1=MTMwMDE3MDQ%3d&VD2=B67E48F6969E99A0BC2BEE0E240D2B5C&SiteLanguage=English";
Pattern p = Pattern.compile("VD1=(.*)&VD2=(.*)&");
Matcher m = p.matcher(test);
while(m.find()){
System.out.println(m.group(1));
System.out.println(m.group(2));
}
}
O/P :
MTMwMDE3MDQ%3d
B67E48F6969E99A0BC2BEE0E240D2B5C
You can use regular expressions or use the String index() and split() methods.
A regular expression that matches and captures the VD1 value is
/VD1=([^&]*)/
If you're sure that theres always a "&" behind the values of VD1 and VD2, this kind of splitting will do:
String test = "DomainName=xyz.zzz.com&ModifiedOn=03%2f17%2f2015&VD1=MTMwMDE3MDQ%3d&VD2=B67E48F6969E99A0BC2BEE0E240D2B5C&SiteLanguage=English";
String vd1 = test.substring(test.indexOf("VD1=")+4, test.indexOf("&", test.indexOf("VD1")));
String vd2 = test.substring(test.indexOf("VD2=")+4, test.indexOf("&", test.indexOf("VD2")));
System.out.println("VD1:" + vd1 + "\nVD2:" + vd2);
This is only a demo, for production you'd have to extract the indexes for better performance.
You can use String.split(...) to split a String in pieces. For example, test.split("&") first splits the String in individual tokens (of the form "key=value").
You could do the following to achieve this:
String vd1 = null, vd2 = null;
for (String token : test.split("&")) {
// For each token, we check if it is one of the keys we need:
if (token.startsWith("VD1=")) {
// The number 4 represents the length of the String "vd1="
vd1 = token.substring(4);
} else if (token.startsWith("VD2=") {
vd2 = token.substring(4);
}
}
System.out.println("VD1 = " + vd1);
System.out.println("VD2 = " + vd2);
However, if you want to parse arbitrary keys, consider using a more robust solution (instead of hard-coding the keys in the for-loop).
Also see the documentation for the String class
String test = "DomainName=xyz.zzz.com&Test&ModifiedOn=03%2f17%2f2015&VD1=MTMwMDE3MDQ%3d&VD2=B67E48F6969E99A0BC2BEE0E240D2B5C&SiteLanguage=English";
HashMap<String, String> paramsMap = new HashMap<String, String>();
String[] params = test.split("&");
for (int i=0; i<params.length; i++) {
String[] param = params[i].split("=");
String paramName = URLDecoder.decode(param[0], "UTF-8");
String paramValue = null;
if(param.length > 1)
paramValue = URLDecoder.decode(param[1], "UTF-8");
paramsMap.put(paramName, paramValue);
}
String vd1 = paramsMap.get("VD1");
String vd2 = paramsMap.get("VD2");
I have the following java code:
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
strTest = strTest + alternativeEntity.getArrivalStation().getName() + ", ";
}
The output looks like this:
nullabc, xyz, oop,
How can I solve this problem and very bad character format? It would be great if I can create output like this:
abc, xyz, oop
Initialize your string to "":
String strTest = "";
Alternatively, you should use a StringBuilder:
StringBuilder builder = new StringBuilder();
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
builder.append(alternativeEntity.getArrivalStation().getName()).append(", ");
}
This will produce better performance.
Initialize strTest as:
String strTest = "";
Also, remove the last comma ,
strTest=strTest.substring(0, strTest.length()-1);
You can use Guava's Joiner#join(Iterable parts). For example:
Joiner joiner = Joiner.on(", ").skipNulls();
String result = joiner.join(list);
System.out.println(result);
Here, all the elements of the list will be printed comma separated without any trailing commas. Also, all the null elements will be skipped.
More info:
Strings Explained
Java provides StringBuilder class just for this purpose,its simple and easy to use..
StringBuilder str = new StringBuilder("India ");
//to append "Hi"
str.append("Hi");
// print the whole string
System.out.println("The string is "+str)
the output will be : The string is India Hi
click here to know more about StringBuilder class
Replace String strTest = null; by String strTest = "";
Change
String strTest = null;
to
String strTest = "";
why don't you use:
String strTest = "";
and at the end:
if(strTest.endsWith(", "))
strTest = strTest.substring(0, strTest.length()-2);
Initialize String strTest="";
For skipping the last comma','
Use outside For loop:
strTest = strTest.substring(0,strTest.trim().length()-1);
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance().getAlternatives()) {
String name = alternativeEntity.getArrivalStation().getName();
strTest = (strTest == null) ? name : strTest + ", " + name;
}
If the list is long, you should use a StringBuilder rather than the String for strTest because the code above builds a fresh string on each iteration: far too much copying.
EDIT :
Goal : http://localhost:8080/api/upload/form/test/test
Is it possible to have some thing like `{a-b, A-B..0-9}` kind of pattern and match them and replace with value.
i have following string
http://localhost:8080/api/upload/form/{uploadType}/{uploadName}
there can be any no of strings like {uploadType}/{uploadName}.
how to replace them with some values in java?
[Edited] Apparently you don't know what substitutions you'll be looking for, or don't have a reasonable finite Map of them. In this case:
Pattern SUBST_Patt = Pattern.compile("\\{(\\w+)\\}");
StringBuilder sb = new StringBuilder( template);
Matcher m = SUBST_Patt.matcher( sb);
int index = 0;
while (m.find( index)) {
String subst = m.group( 1);
index = m.start();
//
String replacement = "replacement"; // .. lookup Subst -> Replacement here
sb.replace( index, m.end(), replacement);
index = index + replacement.length();
}
Look, I'm really expecting a +1 now.
[Simpler approach] String.replace() is a 'simple replace' & easy to use for your purposes; if you want regexes you can use String.replaceAll().
For multiple dynamic replacements:
public String substituteStr (String template, Map<String,String> substs) {
String result = template;
for (Map.Entry<String,String> subst : substs.entrySet()) {
String pattern = "{"+subst.getKey()+"}";
result = result.replace( pattern, subst.getValue());
}
return result;
}
That's the quick & easy approach, to start with.
You can use the replace method in the following way:
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String typevalue = "typeValue";
String nameValue = "nameValue";
s = s.replace("{uploadType}",value).replace("{uploadName}",nameValue);
You can take the string that start from {uploadType} till the end.
Then you can split that string using "split" into string array.
Were the first cell(0) is the type and 1 is the name.
Solution 1 :
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/" + uploadName;
Solution 2:
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/{uploadName}";
url.replace("{uploadName}",uploadName );
Solution 3:
String uploadName = "xyz";
String url = String.format("http://localhost:8080/api/upload/form/ %s ", uploadName);
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String result = s.replace("uploadType", "UploadedType").replace("uploadName","UploadedName");
EDIT: Try this:
String r = s.substring(0 , s.indexOf("{")) + "replacement";
The UriBuilder does exactly what you need:
UriBuilder.fromPath("http://localhost:8080/api/upload/form/{uploadType}/{uploadName}").build("foo", "bar");
Results in:
http://localhost:8080/api/upload/form/foo/bar
I have a string which has the values like this (format is the same):
name:xxx
occupation:yyy
phone:zzz
I want to convert this into an array and get the occupation value using indexes.
Any suggestions?
Basically you would use Java's split() function:
String str = "Name:Glenn Occupation:Code_Monkey";
String[] temp = str.split(" ");
String[] name = temp[0].split(":");
String[] occupation = temp[1].split(":");
The resultant values would be:
name[0] - Name
name[1] - Glenn
occupation[0] - Occupation
occupation[1] - Code_Monkey
Read about Split functnio. You can split your text by " " and then by ":"
I would recommend using String's split function.
Sounds like you want to convert to a property Map rather than an array.
e.g.
String text = "name:xxx occupation:yyy phone:zzz";
Map<String, String> properties = new LinkedHashMap<String, String>();
for(String keyValue: text.trim().split(" +")) {
String[] parts = keyValue.split(":", 2);
properties.put(parts[0], parts[1]);
}
String name = properties.get("name"); // equals xxx
This approach allows your values to be in any order. If a key is missing, the get() will return null.
If you are only interested in the occupation value, you could do:
String s = "name:xxx occupation:yyy phone:zzz";
Pattern pattern = Pattern.compile(".*occupation:(\\S+).*");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
String occupation = matcher.group(1);
}
str = "name:xxx occupation:yyy phone:zzz
name:xx1 occupation:yy3 phone:zz3
name:xx2 occupation:yy1 phone:zz2"
name[0] = str.subtsring(str.indexAt("name:")+"name:".length,str.length-str.indexAt("occupation:"))
occupation[0] = str.subtsring(str.indexAt("occupation:"),str.length-str.indexAt("phone:"))
phone[0] = str.subtsring(str.indexAt("phone:"),str.length-str.indexAt("occupation:"))
I got the solution:
String[] temp= objValue.split("\n");
String[] temp1 = temp[1].split(":");
String Value = temp1[1].toString();
System.out.println(value);
I want to make strings like "a b c" to "prefix_a prefix_b prefix_c"
how to do that in java?
You can use the String method: replaceAll(String regex,String replacement)
String s = "a xyz c";
s = s.replaceAll("(\\w+)", "prefix_$1");
System.out.println(s);
You may need to tweek the regexp to meet your exact requirements.
Assuming a split character of a space (" "), the String can be split using the split method, then each new String can have the prefix_ appended, then concatenated back to a String:
String[] tokens = "a b c".split(" ");
String result = "";
for (String token : tokens) {
result += ("prefix_" + token + " ");
}
System.out.println(result);
Output:
prefix_a prefix_b prefix_c
Using a StringBuilder would improve performance if necessary:
String[] tokens = "a b c".split(" ");
StringBuilder result = new StringBuilder();
for (String token : tokens) {
result.append("prefix_");
result.append(token);
result.append(" ");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
The only catch with the first sample is that there will be an extraneous space at the end of the last token.
hope I'm not mis-reading the question. Are you just looking for straight up concatenation?
String someString = "a";
String yourPrefix = "prefix_"; // or whatever
String result = yourPrefix + someString;
System.out.println(result);
would show you
prefix_a
You can use StringTokenizer to enumerate over your string, with a "space" delimiter, and in your loop you can add your prefix onto the current element in your enumeration. Bottom line: See StringTokenizer in the javadocs.
You could also do it with regex and a word boundary ("\b"), but this seems brittle.
Another possibility is using String.split to convert your string into an array of strings, and then loop over your array of "a", "b", and "c" and prefix your array elements with the prefix of your choice.
You can split a string using regular expressions and put it back together with a loop over the resulting array:
public class Test {
public static void main (String args[]) {
String s = "a b c";
String[] s2 = s.split("\\s+");
String s3 = "";
if (s2.length > 0)
s3 = "pattern_" + s2[0];
for (int i = 1; i < s2.length; i++) {
s3 = s3 + " pattern_" + s2[i];
}
System.out.println (s3);
}
}
This is C# but should easily translate to Java (but it's not a very smart solution).
String input = "a b c";
String output (" " + input).Replace(" ", "prefix_")
UPDATE
The first solution has no spaces in the output. This solution requires a place holder symbol (#) not occuring in the input.
String output = ("#" + input.Replace(" ", " #")).Replace("#", "prefix_");
It's probably more efficient to use a StringBuilder.
String input = "a b c";
String[] items = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (String item in items)
{
sb.Append("prefix_");
sb.Append(item);
sb.Append(" ");
}
sb.Length--;
String output = sb.ToString();