You can use:
String str1 = str.replaceAll("[.]", "");
instead of:
String str1 = str.replaceAll(".", "");
As @nachokk said, you may want to read something about regex, since replaceAll first parameter expects for a regex expression.
Edit:
Or just this:
String str1 = s.replaceAll("[,.]", "");
to make it all in one sentence.
Answer from Christian Tapia on Stack OverflowYou can use:
String str1 = str.replaceAll("[.]", "");
instead of:
String str1 = str.replaceAll(".", "");
As @nachokk said, you may want to read something about regex, since replaceAll first parameter expects for a regex expression.
Edit:
Or just this:
String str1 = s.replaceAll("[,.]", "");
to make it all in one sentence.
You can just use String#replace() instead of replaceAll cause String#replaceAll
Replaces each substring of this string that matches the given regular expression with the given replacement.
So in code with replace is
str = str.replace(",","");
str = str.replace(".","");
Or you could use a proper regular expression all in one:
str = str.replaceAll("[.,]", "");
do like this
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse("\$123,456.78");
System.out.println(number.toString());
output
123456.78
Try,
String liveprice = "$123,456.78";
String newStr = liveprice.replaceAll("[$,]", "");
replaceAll uses regex, to avoid regex than try with consecutive replace method.
String liveprice = "$1,23,456.78";
String newStr = liveprice.replace("$", "").replace(",", "");
java - How to remove all special character in a string except dot and comma - Stack Overflow
java - Remove trailing comma from comma-separated string - Stack Overflow
string - How to replace comma (,) with a dot (.) using java - Stack Overflow
java - remove comma and some characters from a string - Stack Overflow
("[u' %$HI# Jhon,
are *&
").replace(/[^.,a-zA-Z]/g, '');
You need to add comma and dot with all characters inside the brackets, like I just did.
And you might want to include numbers too.
("[u' %$HI# Jhon,
are *&
").replace(/[^.,a-zA-Z0-9]/g, '');
Edited
And, as noted below, your output also needs spaces:
("[u' %$HI# Jhon,
are *&
").replace(/[^.,a-zA-Z ]/g, '');
This might also help:
>>> punctuation = """!\"#$%&'()*+-/:;<=>?@[\\]^_`{|}~"""
>>> string = "[%$HI# Jhon,
are *&
"
>>> edited = ""
>>> for i in string:
... if i not in punctuation:
... edited += i
...
>>> edited
'HI Jhon, how are you.'
To remove the ", " part which is immediately followed by end of string, you can do:
str = str.replaceAll(", $", "");
This handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case.
Example code:
String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str); // prints "kushalhs, mayurvm, narendrabz"
NOTE: Since there has been some comments and suggested edits about the ", $" part: The expression should match the trailing part that you want to remove.
- If your input looks like
"a,b,c,", use",$". - If your input looks like
"a, b, c, ", use", $". - If your input looks like
"a , b , c , ", use" , $".
I think you get the point.
You can use this:
String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));
Your problem is not with the match / replacement, but that String is immutable, you need to assign the result:
str = str.replaceAll(",","."); // or "\\.", it doesn't matter...
Just use replace instead of replaceAll (which expects regex):
str = str.replace(",", ".");
or
str = str.replace(',', '.');
(replace takes as input either char or CharSequence, which is an interface implemented by String)
Also note that you should reassign the result
You could chain some String::replace methods
String str = "'abc','xyz','abc'";
str = str.replace (",'xyz'", "").replace("'xyz',", "").replace("'xyz'", "");
output
'abc','abc'
Regex alone is not very well equipped for this task. However, you can do the following:
- Split your string on comma. In fact, you can split by comma surrounded by any amount of whitespace, in case the sting you get is
"'abc', 'xyz'", for example. You can use the regex\s*,\s*for that. - Remove anything that matches the string you don't want - you can use basic string matching or regex for more complex patterns.
- Convert the split string into a comma separated list again.
Usign Java 8 Stream operations, this can be short:
String[] split = str.split(("\\s*,\\s*")); //1. split into separate strings
String result = Arrays.stream(split) //turn to stream
.filter(chunk -> !"'xyz'".equals(chunk)) //2. remove anything you don't want
.collect(Collectors.joining(",")); //3. convert back to comma separated list
The .filter predicate can be changed to whatever suits you - if you only want to match "'abc'" then you can use chunk -> "abc'".equals(chunk) or you can use .contains or equalsIgnoreCase, or even regex.
It might be worth extracting the filter rule out into a separate Predicate, so you can more easily change it, when needed
Predicate<String> filterRule = chunk -> !"'xyz'".equals(chunk);
/* ... */
.filter(filterRule)
/* ... */
Although if we examine this "'xyz'".equals is already a predicate itself, and predicates can be negated, so you don't need to write a whole lambda for this but just re-use the methods as functional interfaces:
Predicate<String> stuffWeDontWant = "'xyz'"::equals;
Predicate<String> filterRule = stuffWeDontWant.negate();
This can all be inlined but it's a bit ugly, as you have to cast it into the proper predicate to negate it
Predicate<String> filterRule = ((Predicate<String>) "'xyz'"::equals).negate();
The final thing can look like this:
Predicate<String> filterRule = ((Predicate<String>) "'xyz'"::equals).negate();
String result = Arrays.stream(str.split(("\\s*,\\s*")))
.filter(filterRule)
.collect(Collectors.joining(","));
So now you can more easily change whatever your filter rule is. You can even re-use this for any kind of list by just passing different predicate to use as a filter.
A non-Java 8 or non-Stream way to do the same to do the following:
String[] split = str.split(("\\s*,\\s*")); //1. split into separate strings
List<String> list = new ArrayList<>(Arrays.asList(split));//convert into an ArrayList to allow removing
list.removeAll(Collections.singleton("'xyz'"));//2. remove anything you don't want
String result = String.join(",", list); //3. convert back to comma separated list
This approach can still be mixed with using a Predicate by using .removeIf() but this time it has to match exactly what you don't want:
list.removeIf("'xyz'"::equals);
/* or */
list.removeIf("'xyz'"::equalsIgnoreCase);
/* or */
list.removeIf("'xyz'"::startsWith);
/* or */
list.removeIf("'xyz'"::contains);
/* or */
list.removeIf("'xyz'"::endsWith);
/* or */
list.removeIf(Pattern.compile("'(xy?z)*'").asPredicate());
/* ...and so on... */
Here is your answer:
String regex = "(?<=[\\d])(,)(?=[\\d])";
Pattern p = Pattern.compile(regex);
String str = "Your input";
Matcher m = p.matcher(str);
str = m.replaceAll("");
System.out.println(str);
This only affects NUMBERS, not strings, as you asked.
Try adding that in your main method. Or try this one, it receives input:
String regex = "(?<=[\\d])(,)(?=[\\d])";
Pattern p = Pattern.compile(regex);
System.out.println("Value?: ");
Scanner scanIn = new Scanner(System.in);
String str = scanIn.next();
Matcher m = p.matcher(str);
str = m.replaceAll("");
System.out.println(str);
The easiest way is to use two regexes. The first to make sure it is numeric (something along the lines of [0-9.,]*), and the second to clean it (result.replaceAll("/,//"))
import java.io.File; import java.util.ArrayList; import java.util.Scanner;
public class EmailReader {
public static void main(String[] args) throws Exception {
Scanner inputFile = new Scanner(new File("NameList.csv"));
inputFile.nextLine();
ArrayList<String> studentNames = new ArrayList();
ArrayList<String> emails = new ArrayList();
String ender = "@virginia.edu";
while (inputFile.hasNext()) {
String name = inputFile.nextLine().concat("@virginia.edu");
studentNames.add(name);
}
for (int i = 0; i < studentNames.size(); i += 2) {
emails.add(studentNames.get(i));
;
}
System.out.println(emails);
}}
It might be better to fix the code that adds those additional commas.
Anyway, query.replaceAll(",+", ",") will squash any sequence of commas into one. Then you are stuck with the commas around the as keywords. Those you can replace by .replaceAll(",\\s*[Aa][Ss]\\s*,", " as "). Similarly for the other keywords like WHERE, FROM, ...
First of all, you should try to fix the source of that query.
Here is an easy trick avoiding the use of regex:
String query = "SELECT NAME,, AGE,, Dep, as, Department, FROM, Employee, WHERE =, :param1";
query = query.replace(",,", "#").replace(",", "").replace("#", ",");
System.out.println(query);
SELECT NAME, AGE, Dep as Department FROM Employee WHERE = :param1