MOrris Example
Morris.Bar({
element: 'bar-example',
data: [
{ month: "2006", amount: 100},
{ month: "2007", amount: 75}
],
xkey: "month",
ykeys: ["amount"],
labels: ["amount"]
});
amount in ykeys and lables should be same as it is mentioned in Morris Example. Otherwise graph would not display because of error in amount format.
At moment my amount value is in this way
String amount = "[amount]";
amount="[amount]"
and i want value in this way
["amount"]
What would be easiest and preferred way to replace these values?
Why regex?
If you can achieve your task with simple calls to APIs which don't require regex, stick to them.
amount.subString(1,amount.length()-1);
You don't need to use regex.
amount = amount.replace("[", "[\"").replace("]","\"]");
Edited. OP cleared up what was needed. The above code is replacing [ with [" and ] with "].
The " is escaped within java with \
Related
I have sample jsonNode data - Inputstr =
{
"a.b.c.d.e":"123",
"a[0].b.c.d[0].e":"123",
"a[0].b.c.d[1].e":"123",
"a[1].b.c.d[0].e":"123",
"a[1].b.c.d[1].e":"123",
"d.e.f"="789",
"x.y.z"="789"
}
I want to extract the keys having data in format a[0-9*].b[0-9*].c[0-9*].d[0-9*].e[0-9*].
Basically, the output should return me, 0 or more occurrences
[ a.b.c.d.e , a[0].b.c.d[0].e, a[0].b.c.d[1].e, a[1].b.c.d[0].e, a[1].b.c.d[1].e ].
So, what i did was
val json = ObjectMapper.readTree(Inputstr)
val itr = json.fieldNames
Now on this iterator of keys i want to create a generic regex which returns me the above output.
I tried but not working
val regex = """a\[[0-9\]]*.b\[[0-9\]]*.c\[[0-9\]]*.d\[[0-9\]]*.e\[[0-9\]]*""".r
while(itr.hasNext())
{
val str= itr.next()
regex.findAllIn(str)
}
I am stuck in creating the regex basically which can take [0-9]*, it should check for both the braces [ ] as well as presence of a digit from 0 to 9 inside the braces. Even if none exists, it should return me a.b.c.d.e as well.
I hope it makes sense.
Please let me know if any questions.
a(?:\[\d])?\.b(?:\[\d])?\.c(?:\[\d])?\.d(?:\[\d])?\.e(?:\[\d])?
Should do the job, I included the [0] part inside of a non matching group that can be optional using ?
I want to make this so that short inputs can still be detected, such as "Londo" and "Lon", but want to keep it small and use it without basically copying and pasting the code, any tips? thank you.
if (Menu.answer1.equals("London"))
{
if (location.equals("London")) {
System.out.print(location + " ");
System.out.print(date + " ");
System.out.print(degrees + "C ");
System.out.print(wind + "MPH ");
System.out.print(winddirection + " ");
System.out.print(weather + " ");
System.out.println("");
}
You can use startsWith()
String city = "London";
if (city.startsWith("Lon")) {
// do something
}
Also if you need to check some substring, you can use contains method:
Menu.answer1 = "London";
Menu.answer1.contains("ondo"); // true
If you want to check against a fixed set of alternatives, you may use a list of valid inputs using contains:
List<String> londonNames = Arrays.asList("London", "Londo", "Lon");
if (londonNames.contains(Menu.answer1)) {
...
}
You can use (case-insensitive) regex to do the same, e.g.:
(?)Lon[a-z]{0,3} where
(?) = case insensitivity
Lon = Initial 3 characters
[a-z]{0,3} = any number of alphabets between 0 and 3
Here's an example:
String regex = "(?)Lon[a-z]{0,3}";
System.out.println("London".matches(regex));
System.out.println("Lond".matches(regex));
System.out.println("Lon".matches(regex));
If the underlying problem is that the user can enter one of several names, and you want to allow abbreviations, then a fairly standard approach is to have a table of acceptable names.
Given the user input, loop through the table testing "does the table entry start with the string typed by the user?" (like one of the previous answers here). If yes, then you have a potential match.
Keep looking. If you get a second match then the user input was ambiguous and should be rejected.
As a bonus, you can collect all names that match, and then use them in an error message. ("Pick one of London, Lonfoo, Lonbar").
This approach has the advantage (compared to a long chain of if-then-else logic) of not requiring you to write more code when all you want to do is have more data.
It automatically allows the shortest unique abbreviation, and will adjust when a once-unique abbreviation is no longer unique because of newly-added names.
I need split String to array. For exapmle i have string str = "apple fruits money Pacific Ocean".
and I try split to array like this:
String []arr = str.split(" ");
But I need the Pacific Ocean to register in one cell of the array. I can't change the separator, because i get data in this form ("apple fruits money Pacific Ocean").
If we admit that multiple consecutive capitalized words need to be considered as a single word, then you can do:
String []arr = str.split("\\s");
then
`String str = "apple fruits money Pacific Ocean";
String[] arr = str.split("\\s");
String[] finalArr = new String[arr.length];
int i = 0;
for (String word : arr) {
// capitalized
if (Character.isUpperCase(word.charAt(0))) {
// check if previous is capitalized
if (Character.isUpperCase(finalArr[i - 1].charAt(0))) {
finalArr[i - 1] = finalArr[i - 1] + word + " ";
} else {
finalArr[i] = word + " ";
}
} else {
finalArr[i] = word;
}
i++;
}
for (String s : finalArr) {
System.out.println(s);
}
}
}`
will result in:
apple
fruits
money
Pacific Ocean
null
You'll need to filter the nulls though and add some checks (if i-1 exists at all).
You need to change the separator as Elliott Frisch stated in his comment. You're not going to be able to determine whether or not a set of words need to stay together if they contain a space. If your word list were separated by another character (such as a comma) then the problem becomes much easier to solve.
String input = "apples,fruits,money,Pacific Ocean";
String[] arr = input.split(",");
Now your array contains each of the words in input.
The problem as described in the question and comments has no solution.
Consider this:
"banana red apple green apple"
This can be split like this:
["banana", "red", "apple", "green", "apple"]
or like this
["banana", "red apple", "green apple"]
Without semantic / contextual analysis it is impossible to know which is more likely to be correct. And it is impossible to know for sure what the (human) user actually meant.
I can't change the separator, because i get data in this form ("apple fruits money Pacific Ocean").
You need to redesign the form or the input syntax so that your software doesn't need to perform this task. There is no other way ... to always get the correct answer.
Think of it this way. Suppose someone gave you a sequence of words in a foreign language on a piece of paper, and asked you to split them correctly. How would you (a human) solve the problem, assuming that you didn't understand the language, and hadn't been given a dictionary or a set of rules? This is equivalent to the task you are setting the computer ...
This way it's not possible. If the string was joined earlier, try using a character other than space. Maybe the pipe | might be an option.
For example, say I want to write to a text file, and I want to line up my results into columns like so:
Peanut Butter Crunchy
Jelly Purple
Bread Wheat
Milk Whole
\t obviously doesn't line up the second column when the first words are different lengths. Is lining them up possible?
Yes, it is possible. You want to pad the strings to the right with white spaces. For example, if you specify that each column starts every 20 characters and your string is 12 characters, you need to add 8 whitespace characters to the end.
You could hand code a loop or you could use string.format(). I took a look around online and found this easy method which you can use. http://www.rgagnon.com/javadetails/java-0448.html
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
s is the string that you want to pad, n is the ideal length.
For example,
padRight("test", 10") -> "test "
To add to your code, just format each line. For example, for your first line, you could do
String line = padRight(peanutButterString, 20) + peanutButterAttribute
Make sure your values are in an array and you can easily loop through it and create the properly formatted string.
I have a question on how to use printf for multiple formats. I want something like this, where everything inside printf is spaced out evenly:
i i i i i
and this is how I used printf:
// display headers
System.out.printf("", "%15s", "%15s", "%15s", "%15s", "Car Type",
"Starting Miles", "Ending Miles", "Distance/Gallon",
"Gallons/Distance", "Miles/Gallon");
when I executed my program, the above wouldn't show up at all, I just go this:
run:
Gas & Mileage Calculations
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
BUILD SUCCESSFUL (total time: 0 seconds)
Just concatenate the formats:
System.out.printf("%15s%15s%15s%15s", "header 1", "header 2", ...);
The way you use printf() is wrong.
It's first parameter is String format, which will be the formatting string, which implements all further arguments.
Example:
String name = "Chris";
int age = 25;
System.out.printf("%s = %d", name, age);
This will print out "Chris = 25", because %s is converted into the variable name and %d into variable age. Check the API docs for more information.