get rid of square brackets in java - java

I am writing a program in SWI-prolog and Java.
My problem is, when i print the result from prolog in returns with [] and I don't want this.
The code for printing the results is
String t8 = "findDiseases(" + mylist + ",Diseases)."+ "\n";
Query q8 = new Query(t8);
Diagnosis_txt.append("Με τις δοθείσες πληροφορίες πάσχετε από: " +
"\n" +
"\n" +
q8.oneSolution().get("Diseases"));
while (q8.hasMoreSolutions()) {
Map<String, Term> s7 = q8.nextSolution();
System.out.println("Answer is " + s7.get("Diseases"));
}
And the printed results is
Answer is '[|]'(drepanocytocis, '[|]'(drepanocytocis, '[]'))
I want to get rid of this [|] and the []. I want to print only drepanocytocis.

if you want to remove all special characters you can do something like this:
answer = answer.replaceAll("[^a-zA-Z ]+", "").trim();
update
to remove any duplicate spaces after that run, the full solution can do somthing like this:
answer.replaceAll("[^a-zA-Z ]+", " ")
// remove duplicate spaces
.replaceAll("[ ]([ ]+)", " ")
// remove leading & trailing spaces
.trim();
It can then be split on spaces to get the correct sanitized answer...
However, as #andy suggested, I recommend finding the source of the data, and building a proper data structure for it to return exactly what you want. post processing should only kinda be used for data you have no control of, or old versions, etc...

Related

Java String output

My String input is String Number = "546+90".
I want to give output like this "546 + 90".how can i do it in java? Right now I am trying:
Number.replaceAll("[0-9]"," ");
But it doesn't seem to be working. Does anyone have any suggestions?
Strings are immutable so you need to get the string resultant of the replace method:
public static void main(String[] args) {
String number="546+90";
number = number.replaceAll("\\+" , " + ");
System.out.println(number);
}
First, Number is a built-in class in the java.lang package, so you should never use that name.
Second, variables should be written in lower-case, so it should be number.
Third, Strings are immutable, so the need to get the return value from replaceAll().
If you want this string: "String Number=546+90"
to become this string: "546 + 90"
then you need to strip anything before = and add spaces around the +.
This can be done by chaining replace calls:
String number = "String Number=546+90";
number = number.replaceFirst(".*=", "")
.replaceAll("\\+", " + ");
System.out.println(number);
If you want other operators too, use a character class. You have to capture the character to retain it in the replacement string, and you must put - first or last (or escape it).
number = number.replaceFirst(".*=", "")
.replaceAll("([-+*/%])", " $1 ");
Adding an escape characters will solve your problem
String Number = "\"" + "546+90" + "\"";

Match string between multiple brackets

I have this very long JSON string. I would like to filtrate it and only get the data between the first bracket. The problem is, I have many other brackets therefore my regex pattern is not working properly.
Here is the JSON string:
String jsondata = "["
+"{"
+ "test: 63453645"
+"date: 2016-07-17"
"{"
+ "id:534534"
+"}"
+ "blank : null"
+ "flags : null"
+ "}"
+"{"
+ "test: 543564236"
+"date: 2014-07-17"
+"{"
+ "id:6532465"
+"}"
+ "blank : null"
+ "flags : null"
+ "}"
+"]";
pattern = "\\{[^{}]*\\}";
pr = Pattern.compile(pattern);
math = pr.matcher(jsondata);
if (math.find()) {
System.out.println(math.group());
}
else
System.out.println("nomatch");
The problem with the pattern that I have is that it only prints out to the first } after the id:, but I want it to end at the last } which is after flags: null.
And I only want to print the first match, i.e not the string after because the also start and end with the same character, and that is why I have an if statement instead of a while loop.
Any suggestions? Thank you!
Regex with multiple brackets seems like a very difficult task. Can I match the last string instead? Starting from { to flags : null?
Like I said in comment,
I usually make use of JSON-Simple.
A great tutorial, decoding.
would look somewhat like:
JSONObject obj = JSONValue.parse(jsondata);
obj.get("test");
PS.
I do see some errors in your json data, make use of jsonlint to verify if your json is formatted correctly...
This will grab everything between the first { and last }:
String guts = jsondata.replaceAll("(?s)^.*?\\{(.*?flags : null[^}]*).*$", "$1");
The regex captures everything after the first { up to your semaphore text and all non-} chars following.

REGEX to format phone number in java

given a phone number with spaces and + allowed, how would you right a regular expression to format it so that non-digits and extra spaces are removed?
I have this so far
String num = " Ken's Phone is + 123 2213 123 (night time)";
System.out.println(num.replaceAll("[^\\d|+|\\s]", "").replaceAll("\\s\\s+", " ").replaceAll("\\+ ", "\\+").trim());
Would you simplify it so that the same result is obtained?
Thank you
I would put trim() first, or at least before you replace every multiple spaces.
Also keep in mind that \s means whitespaces: [ \t\n\x0B\f\r], if you only mean ' ' then use it.
A nicer way to express that you only want at least two spaces to be replaced would be
replaceAll("\\s{2,}", " ")
First extract the number-with-spaces part, then compress multiple spaces to single spaces. then finally remove all spaces that follow a plus sign:
String numberWithSpaces = str.replaceAll("^[^\\d+]*([+\\d\\s]+)[^\\d]*$", "$1").replaceAll("\\s+", " ").replaceAll("\\+\\s*", "+");
I tested this code and it works.
You can simplify it as:
num.replaceAll("[^\\d+\\s]", "") // [^\\d|+|\\s] => [^\\d+\\s]
.replaceAll("\\s{2,}", " ") // \\s\\s+ => \\s{2,}
.replaceAll("\\+\\s", "+") // \\+ => +
.trim()

Replacing multiple strings with one in java code

I need to replace:
myVariable = "sample string is long " +
"so I put rest of it in 2nd line." +
" And sometimes in 3rd and so on";
with:
myVariable = "sample string is long so I put rest of it in 2nd line. And sometimes in 3rd and so on";
Additional issue: how to merge entities like above I they have other variables in concatenation chain?
myVar = "The number of the beast is " + numberOfTheBeast + " !!! So I said";
What I'd like to do is to change it into single string with params inside.
I'm not a regular expression guru, but these three regex replaces should do the trick. Most IDEs have a regex replace function.
Replace: With:
\s*\+\s*\n + (space, plus, space)
"\s*\+\s*" nothing
\s*\+\s* + (space, plus, space)
You might have to use \s*+\s*\r\n for the first regex, if you are on Windows.

Java String Parsing Without Regular Expressions

From a server, I get strings of the following form:
String x = "fixedWord1:var1 data[[fixedWord2:var2 fixedWord3:var3 data[[fixedWord4] [fixedWord5=var5 fixedWord6=var6 fixedWord7=var7]]] , [fixedWord2:var2 fixedWord3:var3 data[[fixedWord4][fixedWord5=var5 fixedWord6=var6 fixedWord7=var7]]]] fixedWord8:fixedWord8";
(only spaces divide groups of word-var pairs)
Later, I want to store them in a Hashmap, like myHashMap.put(fixedWord1, var1); and so on.
Problem:
Inside the first "data[......]"-tag, the number of other "data[..........]"-tags is variable, and I don't know the length of the string in advance.
I don't know how to process such Strings without resorting to String.split(), which is discouraged by our assignment task givers (university).
I have searched the internet and couldn't find appropriate websites explaining such things.
It would be of great help, if experienced people could give me some links to websites or something like a "diagrammatic plan" so that I could code something.
EDIT:
got mistake in String (off-topic-begin "please don't lynch" off-topic-end), the right string is (changed fixedWord7=var7 ---to---> fixedWord7=[var7]):
String x = "fixedWord1:var1 data[[fixedWord2:var2 fixedWord3:var3 data[[fixedWord4] [fixedWord5=var5 fixedWord6=var6 fixedWord7=[var7]]]] , [fixedWord2:var2 fixedWord3:var3 data[[fixedWord4][fixedWord5=var5 fixedWord6=var6 fixedWord7=[var7]]]]] fixedWord8:fixedWord8";
I assume your string follows a same pattern, which has "data" and "[", "]" in it. And the variable name/value will not include these strings
remove string "data[", "[", "]", and "," from the original string
replaceAll("data[", "")
replaceAll("[", "")
etc
separate the string by space: " " by using StringTokenizer or loop through the String char by char.
then you will get array of strings like
fixedWorld1:var1
fixedWorld2:var2
......
fixedWorld4
fixedWorld5=var5
......
then again separate the sub strings by ":" or "=". and put the name/value into the Map
Problem is not absolutely clear but may be something like this will work for you:
Pattern p = Pattern.compile("\\b(\\w+)[:=]\\[?(\\w+)");
Matcher m = p.matcher( x );
while( m.find() ) {
System.out.println( "matched: " + m.group(1) + " - " + m.group(2) );
hashMap.put ( m.group(1), m.group(2) );
}

Categories