I have a big text files and I want to remove everything that is between
double curly brackets.
So given the text below:
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
String cleanedText = Pattern.compile("(?<=\\{\\{).*?\\}\\}", Pattern.DOTALL).matcher(text).replaceAll("");
System.out.println(cleanedText);
I want the output to be:
This is what I want.
I have googled around and tried many different things but I couldn't find anything close to my case and as soon as I change it a little bit everything gets worse.
Thanks in advance
You can use this :
public static void main(String[] args) {
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
String cleanedText = text.replaceAll("\\n", "");
while (cleanedText.contains("{{") && cleanedText.contains("}}")) {
cleanedText = cleanedText.replaceAll("\\{\\{[a-zA-Z\\s]*\\}\\}", "");
}
System.out.println(cleanedText);
}
A regular expression cannot express arbitrarily nested structures; i.e. any syntax that requires a recursive grammar to describe.
If you want to solve this using Java Pattern, you need to do it by repeated pattern matching. Here is one solution:
String res = input;
while (true) {
String tmp = res.replaceAll("\\{\\{[^}]*\\}\\}", "");
if (tmp.equals(res)) {
break;
}
res = tmp;
}
This is not very efficient ...
That can be transformed into an equivalent, but more concise form:
String res = input;
String tmp;
while (!(tmp = res.replaceAll("\\{\\{[^}]*\\}\\}", "")).equals(res)) {
res = tmp;
}
... but I prefer the first version because it is (IMO) a lot more readable.
I am not an expert in regular expression, so I just write a loop which does this for you. If you don't have/want to use a regEx, then it could be helpful for you;)
public static void main(String args[]) {
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
int openBrackets = 0;
String output = "";
char[] input = text.toCharArray();
for(int i=0;i<input.length;i++){
if(input[i] == '{'){
openBrackets++;
continue;
}
if(input[i] == '}'){
openBrackets--;
continue;
}
if(openBrackets==0){
output += input[i];
}
}
System.out.println(output);
}
My suggestion is to remove anything between curly brackets, starting at the innermost pair:
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
Pattern p = Pattern.compile("\\{\\{[^{}]+?}}", Pattern.MULTILINE);
while (p.matcher(text).find()) {
text = p.matcher(text).replaceAll("");
}
resulting in the output
This is
what I
want.
This might fail when having single curly brackets or unpaired pair of brackets, but could be good enough for your case.
I have a file which contains double quotes only to String types but i need to add missing double quotes to other fields and write into a file using java.
for example
123 ,6 ,"abc#yahoo.com"
"
should be converted to
"123 ","6 ","abc#yahoo.com" "
without trimming any value just adding the missing text qualifier around the fields. I have tried by splitting based on delimiter and then wrapping around quotes but it did not work.
please share if you have solved any issue like this.
You need to use string.replaceAll method.
string.replaceAll("(^|,)(?!\")([^,]+)", "$1\"$2\"");
DEMO
There's a solution without such a complicated regular expressions: you have to split your input by , and wrap the resulting Strings:
String[] splitted = input.split(",");
for (int i = 0; i < splitted.size(); ++i) {
if (splitted[i].charAt(0) != '"') {
splitted[i] = "\"" + splitted[i] + "\"";
}
}
String output = String.join(",", Arrays.asList(splitted)); // or any other joining technic, this is from Java 8
You can easily do it by using split() method from String class and just add quote when you need it.
Basically, I would try something like this:
public static void main (String... args) {
String st = "123 ,6 ,\"abc#yahoo.com";
String[] results = st.split(",");
String result = "";
for (String s : results) {
if (!s.startsWith("\""))
s = "\"" + s + "\"";
if (!s.endsWith("\""))
s+="\"";
s+=",";
result += s;
}
System.out.println(st);
System.out.println("-------------");
System.out.println(result);
}
This keep spaces and add some missing quotes.
I tried and the below is working...
public static void test()
{
String str = "123 ,6 ,\"abc#yahoo.com \"";
String result = "",temp="";
StringTokenizer token = new StringTokenizer(str,",");
while(token.hasMoreTokens())
{
temp = token.nextToken();
if(!temp.startsWith("\""))
result += "\""+temp+"\"";
else
result += temp;
}
System.out.println(result);
}
Please check...
Try using a simple foreach and if loop to check if the value has double quotes then add quotes to the values.
for(Object obj:YourContainer){
if(!value.contains("\"")){
String s = "\"" + value + "\"";
}
}
If you are getting fields like ""Test"" with double double quotes, try using the replace function.
String s;
for(Object obj:YourContainer){
if(!value.contains("\"")){
s = "\"" + value + "\"";
}
s = s.replace("\"\"","\"");
}
How to detect the letters in a String and switch them?
I thought about something like this...but is this possible?
//For example:
String main = hello/bye;
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
}else{
//nothing
}
Well, if you are interested in a cheeky regex :P
public static void main(String[] args) {
String s = "hello/bye";
//if(s.contains("/")){ No need to check this
System.out.println(s.replaceAll("(.*?)/(.*)", "$2/$1")); // () is a capturing group. it captures everything inside the braces. $1 and $2 are the captured values. You capture values and then swap them. :P
//}
}
O/P :
bye/hello --> This is what you want right?
Use String.substring:
main = main.substring(main.indexOf("/") + 1)
+ "/"
+ main.substring(0, main.indexOf("/")) ;
You can use String.split e.g.
String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.
String newString = splitUp[1] + "/" + splitUp[0];
Of course you have to also implement some error handling when there is no slash etc..
you can use string.split(separator,limit)
limit : Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array
String main ="hello/bye";
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
String[] parts = main.split("/",1);
main = parts[1] +"/" + parts[0] ; //main become 'bye/hello'
}else{
//nothing
}
Also you can use StringTokenizer to split the string.
String main = "hello/bye";
StringTokenizer st = new StringTokenizer(main,"\");
String part1 = st.nextToken();
String part2 = st.nextToken();
String newMain = part2 + "\" + part1;
I want to add Two java JSON String manually , so for this i need to remove "}" and replace it with comma "," of first JSON String and remove the first "{" of the second JSON String .
This is my program
import java.util.Map;
import org.codehaus.jackson.type.TypeReference;
public class Hi {
private static JsonHelper jsonHelper = JsonHelper.getInstance();
public static void main(String[] args) throws Exception {
Map<String, Tracker> allCusts = null;
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String B = "{\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String totalString = A + B;
if (null != totalString) {
allCusts = (Map<String, Tracker>) jsonHelper.toObject(
totalString, new TypeReference<Map<String, Tracker>>() {
});
}
System.out.println(allCusts);
}
}
When adding two Strings A + B
I want to remove the last character of "}" in A and replace it with "," and remove the FIrst character of "{" in B .
SO this should it look like .
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1},";
String B = "\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
I have tried
String Astr = A.replace(A.substring(A.length()-1), ",");
String Bstr = B.replaceFirst("{", "");
String totalString = Astr + Bstr ;
With this i was getting
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
please suggest .
{ is a control character for Regular Expressions, and since replaceFirst takes a string representation of a Regular Expression as its first argument, you need to escape the { so it's not treated as a control character:
String Bstr = B.replaceFirst("\\{", "");
I would say that using the replace methods is really overkill here since you're just trying to chop a character off of either end of a string. This should work just as well:
String totalString = A.substring(0, A.length()-1) + "," + B.substring(1);
Of course, regex doesn't look like a very good tool for this. But the following seem to work:
String str = "{..{...}..}}";
str = str.replaceFirst("\\{", "");
str = str.replaceFirst("}$", ",");
System.out.println(str);
Output:
..{...}..},
Some issues in your first two statements. Add 0 as start index in substring method and leave with that. Put \\ as escape char in matching pattern and ut a , in second statement as replacement value.
String Astr = A.substring(0, A.length()-1);//truncate the ending `}`
String Bstr = B.replaceFirst("\\{", ",");//replaces first '{` with a ','
String totalString = Astr + Bstr ;
Please note: There are better ways, but I am just trying to correct your statements.
Looking for quick, simple way in Java to change this string
" hello there "
to something that looks like this
"hello there"
where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.
Something like this gets me partly there
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
but not quite.
Try this:
String after = before.trim().replaceAll(" +", " ");
See also
String.trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
regular-expressions.info/Repetition
No trim() regex
It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
There are 3 alternates:
^_+ : any sequence of spaces at the beginning of the string
Match and replace with $1, which captures the empty string
_+$ : any sequence of spaces at the end of the string
Match and replace with $1, which captures the empty string
(_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle
Match and replace with $1, which captures a single space
See also
regular-expressions.info/Anchors
You just need a:
replaceAll("\\s{2,}", " ").trim();
where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).
To test this out quickly try:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
and it will return:
"hello there"
Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here
This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");
trim() method removes the leading and trailing spaces and using replaceAll("regex", "string to replace") method with regex "\s+" matches more than one space and will replace it with a single space
myText = myText.trim().replaceAll("\\s+"," ");
The following code will compact any whitespace between words and remove any at the string's beginning and end
String input = "\n\n\n a string with many spaces, \n"+
" a \t tab and a newline\n\n";
String output = input.trim().replaceAll("\\s+", " ");
System.out.println(output);
This will output a string with many spaces, a tab and a newline
Note that any non-printable characters including spaces, tabs and newlines will be compacted or removed
For more information see the respective documentation:
String#trim() method
String#replaceAll(String regex, String replacement) method
For information about Java's regular expression implementation see the documentation of the Pattern class
"[ ]{2,}"
This will match more than one space.
String mytext = " hello there ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);
OUTPUT:
hello there
To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext.replaceAll("( )+", " ").
You can first use String.trim(), and then apply the regex replace command on the result.
Try this one.
Sample Code
String str = " hello there ";
System.out.println(str.replaceAll("( +)"," ").trim());
OUTPUT
hello there
First it will replace all the spaces with single space. Than we have to supposed to do trim String because Starting of the String and End of the String it will replace the all space with single space if String has spaces at Starting of the String and End of the String So we need to trim them. Than you get your desired String.
String blogName = "how to do in java . com";
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");
trim()
Removes only the leading & trailing spaces.
From Java Doc,
"Returns a string whose value is this string, with any leading and trailing whitespace removed."
System.out.println(" D ev Dum my ".trim());
"D ev Dum my"
replace(), replaceAll()
Replaces all the empty strings in the word,
System.out.println(" D ev Dum my ".replace(" ",""));
System.out.println(" D ev Dum my ".replaceAll(" ",""));
System.out.println(" D ev Dum my ".replaceAll("\\s+",""));
Output:
"DevDummy"
"DevDummy"
"DevDummy"
Note: "\s+" is the regular expression similar to the empty space character.
Reference : https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html
In Kotlin it would look like this
val input = "\n\n\n a string with many spaces, \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")
A lot of correct answers been provided so far and I see lot of upvotes. However, the mentioned ways will work but not really optimized or not really readable.
I recently came across the solution which every developer will like.
String nameWithProperSpacing = StringUtils.normalizeSpace( stringWithLotOfSpaces );
You are done.
This is readable solution.
You could use lookarounds also.
test.replaceAll("^ +| +$|(?<= ) ", "");
OR
test.replaceAll("^ +| +$| (?= )", "")
<space>(?= ) matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.
Example:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$| (?= )", "")
);
}
See String.replaceAll.
Use the regex "\s" and replace with " ".
Then use String.trim.
String str = " hello world"
reduce spaces first
str = str.trim().replaceAll(" +", " ");
capitalize the first letter and lowercase everything else
str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
you should do it like this
String mytext = " hello there ";
mytext = mytext.replaceAll("( +)", " ");
put + inside round brackets.
String str = " this is string ";
str = str.replaceAll("\\s+", " ").trim();
This worked for me
scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();
where filter is following function and scan is the input string:
public String filter(String scan, String regex, String replace) {
StringBuffer sb = new StringBuffer();
Pattern pt = Pattern.compile(regex);
Matcher m = pt.matcher(scan);
while (m.find()) {
m.appendReplacement(sb, replace);
}
m.appendTail(sb);
return sb.toString();
}
The simplest method for removing white space anywhere in the string.
public String removeWhiteSpaces(String returnString){
returnString = returnString.trim().replaceAll("^ +| +$|( )+", " ");
return returnString;
}
check this...
public static void main(String[] args) {
String s = "A B C D E F G\tH I\rJ\nK\tL";
System.out.println("Current : "+s);
System.out.println("Single Space : "+singleSpace(s));
System.out.println("Space count : "+spaceCount(s));
System.out.format("Replace all = %s", s.replaceAll("\\s+", ""));
// Example where it uses the most.
String s = "My name is yashwanth . M";
String s2 = "My nameis yashwanth.M";
System.out.println("Normal : "+s.equals(s2));
System.out.println("Replace : "+s.replaceAll("\\s+", "").equals(s2.replaceAll("\\s+", "")));
}
If String contains only single-space then replace() will not-replace,
If spaces are more than one, Then replace() action performs and removes spacess.
public static String singleSpace(String str){
return str.replaceAll(" +| +|\t|\r|\n","");
}
To count the number of spaces in a String.
public static String spaceCount(String str){
int i = 0;
while(str.indexOf(" ") > -1){
//str = str.replaceFirst(" ", ""+(i++));
str = str.replaceFirst(Pattern.quote(" "), ""+(i++));
}
return str;
}
Pattern.quote("?") returns literal pattern String.
My method before I found the second answer using regex as a better solution. Maybe someone needs this code.
private String replaceMultipleSpacesFromString(String s){
if(s.length() == 0 ) return "";
int timesSpace = 0;
String res = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' '){
timesSpace++;
if(timesSpace < 2)
res += c;
}else{
res += c;
timesSpace = 0;
}
}
return res.trim();
}
Stream version, filters spaces and tabs.
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
I know replaceAll method is much easier but I wanted to post this as well.
public static String removeExtraSpace(String input) {
input= input.trim();
ArrayList <String> x= new ArrayList<>(Arrays.asList(input.split("")));
for(int i=0; i<x.size()-1;i++) {
if(x.get(i).equals(" ") && x.get(i+1).equals(" ")) {
x.remove(i);
i--;
}
}
String word="";
for(String each: x)
word+=each;
return word;
}
String myText = " Hello World ";
myText = myText.trim().replace(/ +(?= )/g,'');
// Output: "Hello World"
string.replaceAll("\s+", " ");
If you already use Guava (v. 19+) in your project you may want to use this:
CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');
or, if you need to remove exactly SPACE symbol ( or U+0020, see more whitespaces) use:
CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');
public class RemoveExtraSpacesEfficient {
public static void main(String[] args) {
String s = "my name is mr space ";
char[] charArray = s.toCharArray();
char prev = s.charAt(0);
for (int i = 0; i < charArray.length; i++) {
char cur = charArray[i];
if (cur == ' ' && prev == ' ') {
} else {
System.out.print(cur);
}
prev = cur;
}
}
}
The above solution is the algorithm with the complexity of O(n) without using any java function.
Please use below code
package com.myjava.string;
import java.util.StringTokenizer;
public class MyStrRemoveMultSpaces {
public static void main(String a[]){
String str = "String With Multiple Spaces";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}