Replace special character in a String - java

I have to replace a string whit special character like this: XY_Universit�-WWWWW-ZZZZZ in another one like: XY_Universita-WWWWW-ZZZZZ.
I tried solutions like stringToReplace.replaceAll(".*Universit.*", "Universita"); but it replace all the string with the word ''Universita" and it isn't what i want.

stringToReplace.replaceAll("Universit[^a]", "Universita")

public static void main(String[] args) throws IOException {
String exp = "XY_Universit�-WWWWW-ZZZZZ";
exp = exp.replaceAll("[^\\w\\s\\-_]", "");
System.out.println(exp);
}
output
XY_Universit-WWWWW-ZZZZZ

You have to be lazy :P
use : .*?XY_Universit. to select only the first XY_universit
demo here

Another odd way..
String example = "XY_Universit�-WWWWW-ZZZZZ";
char ch = 65533; //find ascii of special char
System.out.println(example.replace(ch, 'a'));

Related

Java Regex How to Find if String Contains Characters but order is not a matter

I have String like this "abcdefgh"
I want to check the string contains the following characters [fcb]
Condition is : The string must contain all characters in any order.
How to write a regex for this one.
I tried following regexes :
.*[fcb].* ---> In this case it not check all characters. If any one character matchs it will return true
Don't use regex. Just use String.contains to test for each of the characters in turn:
in.contains("f") && in.contains("c") && in.contains("b")
You could get the char arry and sort it. Afterwards you could check if it contains .*b.*c.*f.*.
public static boolean contains(String input) {
char[] inputChars = input.toCharArray();
Arrays.sort(inputChars);
String bufferInput = String.valueOf(inputChars);
// Since it is sorted this will check if it simply contains `b,c and f`.
return bufferInput.matches(".*b.*c.*f.*");
}
public static void main(String[] args) {
System.out.println(contains("abcdefgh"));
System.out.println(contains("abdefgh"));
}
output:
true
false
this will check if all the letters are present in the string.
public class Example {
public static void main(String args[]) {
String stringA = "abcdefgh";
String opPattern = "(?=[^ ]*f)(?=[^ ]*c)(?=[^ ]*b)[^ ]+";
Pattern opPatternRegex = Pattern.compile(opPattern);
Matcher matcher = opPatternRegex.matcher(stringA);
System.out.println(matcher.find());
}
}
You can use positive lookahead for this
(?=.*b)(?=.*c)(?=.*f)
Not very efficient but easy to understand:
if (s.matches(".*b.*") && s.matches(".*c.*") && s.matches(".*f.*"))

Find a specific word and replace that before the "letter" rather than after

I have an alphabet which I want to replace before any alphabet rather than the after. For example if I have a word "instant" I want to make sure that char 'a' after the 't' should be before the 't'. It should be insatnt. Wherever any of the word has an 'a' it should be replaced before but not after. Is there any possible way out of this?
You have only given one example, so I can't post a general answer. Maybe you can generalize it:
String input = "instant";
String replaced = input.replaceAll("(\\w)a", "a$1");
You can use regex to do what you want.
In the general case you want to replace <something>a by a<something> where <something> is a single character, any character.
In regex this is replacing (\\w)a by a$1, i.e. find cases where an a is preceded by something and capture that something. Then replace it with the a followed by the captured something:
public static void main(String[] args) throws Exception {
final String s = "instant";
System.out.println(s.replaceAll("(\\w)a", "a$1"));
}
Output:
insatnt
The old-school way would be something along the following:
char reference_char = 'a';
String old_string = "instant";
char[] test_array = old_string.toCharArray();
int i = 0;
for (char c : test_array) {
if (i > 0) {
if (c == reference_char) {
test_array[i] = test_array[i - 1];
test_array[i - 1] = reference_char;
}
}
++i;
}
String new_string = new String(test_array);
System.out.println(new_string);
I hope I understood your question.
All the best!

Replacing multiple char from a string in java

I have a PHP script <?=str_replace(array('(',')','-',' ','.'), "", $rs["hq_tel"])?> this is a string replace function that take array of chars and replace them if find any of the char in string. Is there any java equivalent of the function. I found some ways but some are using loop and some repeating the statements but not found any single line solution like this in java.
Thanks in advance.
You can use a regex like this:
//char1, char2 will be replaced by the replacement String. You can add more characters if you want!
String.replaceAll("[char1char2]", "replacement");
where the first parameter is the regex and the second parameter is the replacement.
Refer the docs on how to escape special characters(in case you need to!).
your solution is here..
Replace all special character
str.replaceAll("[^\\dA-Za-z ]", "");
Replace specific special character
str.replaceAll("[()?:!.,;{}]+", " ");
If you don't know about regex you can use something more elaborated:
private static ArrayList<Character> special = new ArrayList<Character>(Arrays.asList('(', ')', '-', ' ', '.'));
public static void main(String[] args) {
String test = "Hello(how-are.you ?";
String outputText = "";
for (int i = 0; i < test.length(); i++) {
Character c = new Character(test.charAt(i));
if (!special.contains(c))
outputText += c;
else
outputText += "";
}
System.out.println(outputText);
}
Output:
Hellohowareyou?
EDIT (without loop but with regex):
public static void main(String[] args) {
String test = "Hello(how-are.you ?)";
String outputText = test.replaceAll("[()-. ]+", "");
System.out.println(outputText);
}
String.replaceAll(String regex, String replacement)

How to get alphabets only from given albha-numberic word in java?

sorry for this if this is a silly question.but i need to know about this.
If i have a word like alphabets,numeric and special charters. I need to extract alphabets only.No need for numeric and special characters.I need to know is there default function is there in Java to split characters only?
eg.String word="te123##st";
I need test only.
This solution works with accentued/non-ascii caracters :
"te123##st\néàø_".replaceAll("[\\p{Digit}\\p{Punct}\\p{Space}]", "");
try this word.replaceAll("[^a-zA-Z]", "");
This will remove all non alphanumeric characters, but it will still remove accented characters.
String word = "te123##st";
word = word.replaceAll("[^\\p{Alpha}]", "");
// or word = word.replaceAll("[\\P{Alpha}]", "");
See apidoc reference.
try
word = word.replaceAll("\\P{Alpha}", "");
String word = "te123##st";
word = word.replaceAll("[\\W\\d._]", "");
try this:
word = word.replaceAll("[\\d##_]", "");
- I won't make this complicated using Regex, but will use inbuilt Java functionalities to answer this.
- First use subString() method to get the "abcd" part of the String, then use toCharArray() method to break the String into char elements, then use Character class's isDigit() method to know whether its a digit or not.
public class T1 {
public static void main(String[] args){
String s = "te123##st";
String str = s.substring(0,4);
System.out.println(str);
String tempStr = new String();
char[] cArr = str.toCharArray();
for(char a :cArr){
if(Character.isAlphabetic(a)){
System.out.println(a+" is a alphabet");
tempStr = tempStr + a;
}else{
System.out.println(a+" is not a alphabet");
}
}
System.out.println("The extracted String is: "+tempStr);
}
}

How to use replace(char, char) to replace all instances of character b with nothing

How do i use replace(char, char) to replace all instances of character "b" with nothing.
For example:
Hambbburger to Hamurger
EDIT: Constraint is only JDK 1.4.2, meaning no overloaded version of replace!
There's also a replaceAll function that uses strings, note however that it evals them as regexes, but for replacing a single char will do just fine.
Here's an example:
String meal = "Hambbburger";
String replaced = meal.replaceAll("b","");
Note that the replaced variable is necessary since replaceAll doesn't change the string in place but creates a new one with the replacement (String is immutable in java).
If the character you want to replace has a different meaning in a regex (e.g. the . char will match any char, not a dot) you'll need to quote the first parameter like this:
String meal = "Ham.bur.ger";
String replaced = meal.replaceAll(Pattern.quote("."),"");
Strings are immutable, so make sure you assign the result to a string.
String str = "Hambbburger";
str = str.replace("b", "");
You don't need replaceAll if you use Java 6. See here: replace
Try this code....
public class main {
public static void main(String args[]){
String g="Hambbburger.i want to eat Hambbburger. ";
System.out.print(g);
g=g.replaceAll("b", "");
System.out.print("---------After Replacement-----\n");
System.out.print(g);
}
}
output
Hambbburger.i want to eat Hambbburger. ---------After Replacement-----
Hamurger.i want to eat Hamurger.
String text = "Hambbburger";
text = text.replace('b', '\0');
The '\0' represents NUL in ASCII code.
replaceAll in String doesnot work properly .It's Always recomend to use replace()
Ex:-
String s="abcdefabcdef";
s=s.replace("a","");
String str="aabbcc";
int n=str.length();
char ch[]=str.toCharArray();
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(ch[i]==ch[j])
{
ch[j]='*';
}
}
}
String temp=new String(ch);
for(int i=0;i<temp.length();i++)
{
if(temp.charAt(i)!='*')
System.out.print(temp.charAt(i));
}

Categories