How to remove commas at the end of any string - java

I have Strings "a,b,c,d,,,,, ", ",,,,a,,,,"
I want these strings to be converted into "a,b,c,d" and ",,,,a" respectively.
I am writing a regular expression for this. My java code looks like this
public class TestRegx{
public static void main(String[] arg){
String text = ",,,a,,,";
System.out.println("Before " +text);
text = text.replaceAll("[^a-zA-Z0-9]","");
System.out.println("After " +text);
}}
But this is removing all the commas here.
How can write this to achieve as given above?

Use :
text.replaceAll(",*$", "")
As mentioned by #Jonny in comments, can also use:-
text.replaceAll(",+$", "")

Your first example had a space at the end, so it needs to match [, ]. When using the same regular expression multiple times, it's better to compile it up front, and it only needs to replace once, and only if at least one character will be removed (+).
Simple version:
text = text.replaceFirst("[, ]+$", "");
Full code to test both inputs:
String[] texts = { "a,b,c,d,,,,, ", ",,,,a,,,," };
Pattern p = Pattern.compile("[, ]+$");
for (String text : texts) {
String text2 = p.matcher(text).replaceFirst("");
System.out.println("Before \"" + text + "\"");
System.out.println("After \"" + text2 + "\"");
}
Output
Before "a,b,c,d,,,,, "
After "a,b,c,d"
Before ",,,,a,,,,"
After ",,,,a"

Related

.contains() not finding multiple lines in java

im trying to do string .contains() for specific lines on text
im reading in lines of a file using Files.readAlllines.
im trying to do
Path c1=Paths.get(prop.getProperty("testPWP"));
List<String> newLines1 = new ArrayList<String>();
for (String line : Files.readAllLines(c1, StandardCharsets.UTF_8)) {
if (line.contains("return test ;\r\n" + " }")) {
newLines1.add( line.replace("return test ;\r\n" +
" }", "return test ;\r\n" +
" }*/"));
}
else {
newLines1.add(line);
}
}
Files.write(c1, newLines1, StandardCharsets.UTF_8);
im basically trying to comment the } after the return statement but the contains function not recongnizing it as its in new line in the file.
Any help on this issue?
As you may have noticed, Files.readAllLines reads all lines and returns a list in which each string represents a line. To accomplish what you are trying to do, you either need to read the entire file into a single string, or concatenate the strings you already have, or change your approach of substitution. The easiest way would be to read the entire contents of the file into one string, which can be accomplished as follows:
String content = new String(Files.readAllBytes(Paths.get("path to file")));
or if you are using Java 11 or higher:
String content = Files.readString(Paths.get("path to file"));
You can use the replaceable parameter to replace the regex.
Demo:
public class Main {
public static void main(String[] args) {
String find = "return test ;\r\n" + " }";
String str = "Hello return test ;\r\n" + " } Hi Bye";
boolean found = str.contains(find);
System.out.println(found);
if (found) {
str = str.replaceAll("(" + find + ")", "/*$1*/");
}
System.out.println(str);
}
}
Output:
true
Hello /*return test ;
}*/ Hi Bye
Here $1 specifies the capturing group, group(1).
In your program, the value of str can be populated as follows:
String str = Files.readString(path, StandardCharsets.US_ASCII);
In case your Java version is less than 11, you do it as follows:
String str = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.US_ASCII);

Unwanted elements appearing when splitting a string with multiple separators in Java

I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
System.out.println("spart[4]: " + spart[4]);
But, I am getting some elements which are blank. The output is:
spart[0]: s
spart[1]: film
spart[2]:
spart[3]: fever
spart[4]: normal
My desired output is:
spart[0]: s
spart[1]: film
spart[2]: fever
spart[3]: normal
spart[4]: curse
Try with this:
public static void main(String[] args) {
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s]+");
for (String string : spart) {
System.out.println("'"+string+"'");
}
}
output:
's'
'film'
'fever'
'normal'
'curse'
I believe it is because you have a Greedy quantifier for space at the end there. I think you would have to use an escape sequence for the plus sign too.
String spart = s.replaceAll( "\\W", " " ).split(" +");

Write method that puts the word "like" in between each of the words in the original sentence

I need to write a method that puts the word "like" in between each of the words in the original sentence.
For example:
teenTalk("That is so funny!")
would return "That like is like so like funny!"
Would you use sentence split for this?
You can do it like this:
String teenTalk(String source) {
return String.join(" like ", source.split(" "));
}
or like this:
String teenTalk(String source) {
return source.replaceAll(" ", " like ");
}
You can replace the space character with "like":
text.replace(" ", " like ");
Using Java 8 :
public static void main(String[] args) {
String testJoiner = "That is so funny!";
// Split the string into list of word
List<String> splited = Arrays.asList(testJoiner.split("\\s"));
// create new StringJoiner that add the delimiter like between each entry
StringJoiner joiner = new StringJoiner(" like ");
// internal iteration over the words and adding them into the joiner
splited.forEach(joiner::add);
// printing the new value
System.out.println(joiner.toString());
}
Not very efficient but the first thing that comes to mind is something "like" this:
import java.util.StringTokenizer;
public String teenTalk(String inputString) {
String liked = "";
StringTokenizer token = new StringTokenizer(inputString);
while (token.hasMoreElements()) {
liked += token.nextToken();
if (token.hasMoreElements()) {
liked += " like ";
}
}
return liked;
}
You can do something like this
String text = "That is so funny!";
text = text.replaceAll("\\s\\b", " like ");
This will also make sure that all " like " 's come in between sentence. It will always put the "like" in between the text, not in the start or at the end. Even if the text is something like this "This is so funny! " it will work.
What about just replacing " " by " like " ?
http://www.tutorialspoint.com/java/java_string_replace.htm

Java Pattern Matcher single or multiple with comma separated

I have a string, which I need to parse, I want to use pattern matcher
need help with pattern.
if string as below:
sometext : test1,test2
output should be:
test1
test2
if input string is :
sometext : test1
then output should be :
test1
as you can see, it can be multiple or single.
So, you just need to replace , with a space? I would suggest a simple
String output = sometext.replace(",", " ");
If you need a newline after the first word, you can do
String output = sometext.replace(",", System.getProperty("line.separator"));
instead.
If "sometext : " is included in the input, you can get rid of that first in the same way:
String output = input.replace("sometext : ", "").replace(",", " ");
First, you have to separate "test1,test2" from "sometext", then use replaceAll to get the tests array by the , token.
String foo = "sometext : test1,test2";
String[] fooArr = foo.split("[:]");
String tests = fooArr[1];
System.out.println(tests.replaceAll(",", " "));
​

removing space before new line in java

i have a space before a new line in a string and cant remove it (in java).
I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}

Categories