replaceAll Dangling metacharacter [duplicate] - java

This question already has answers here:
replace String with another in java
(7 answers)
Closed 7 years ago.
I have a string, say 1++++----2 and I want to replace ++++---- with a certain string, say string.
The I use the java function replaceAll, but it keep warning Dangling metacharacter every time I use it:
mystring.replaceAll("++++----", "string");

Escape the +, only the first or all doesn't matter here.
String str = "1+++---2";
str = str.replaceAll("\\+\\+\\+---", "");
System.out.println(str);
Output:
12
Or use replaceAllas it's meant to be used:
str = str.replaceAll("[+-]", "");

replaceAll's first argument takes a regualr expression and + have special meaning in regualr expression. Escape + to make it work properly .
mystring.replaceAll("\\+\\+\\+\\+----", "string");

You can use following regex :
mystring.replaceAll("\\++-+", "string")
Since + is a regex character you need to escape it.so here in "\\++-+" the first part \\+ will match the character + literally and the second + will match 1 or more combination of character + and the rest is -+ which will match 1 or more -.

When you replace a fixed string, you need a replace function:
String mystring = "1++++----2";
System.out.println(mystring.replace("++++----", "string"));
See demo
Otherwise, you need a regex with replaceAll.
System.out.println(mystring.replaceAll("[+]+-+", "string"));
Note that you do not need to escape the + inside a regex character class, which is convenient in Java.

Related

String#replaceAll() method not replacing for $ (dollar) [duplicate]

This question already has answers here:
Java regular expressions and dollar sign
(5 answers)
Closed 6 years ago.
I've tried built-in method String#replaceAll() to replace all "$" from my String content. But it's not working.
String ss = "HELLO_$_JAVA";
System.out.println(ss.indexOf("$"));
System.out.println(ss);
ss = ss.replaceAll("$", "");
System.out.println(ss);// 'HELLO__JAVA' is expected
OUTPUT:
6
HELLO_$_JAVA
HELLO_$_JAVA
Expected output:
6
HELLO_$_JAVA
HELLO__JAVA
EDIT:
Although Java regular expressions and dollar sign covers the answer, but still my question may be helpful for someone who is facing same problem when using String#replaceAll().
And
Difference between String replace() and replaceAll() also may be helpful.
Two possible solution of that question is
ss = ss.replace("$", "");
OR
ss = ss.replaceAll("\\$", "");
The first parameter of the replaceAll method takes a regular expression, not a literal string, and $ has a special meaning in regular expressions.
You need to escape the $ by putting a backslash in front of it; and the backslash needs to be double because it has a special meaning in Java string literals.
ss = ss.replaceAll("\\$", "");
String.replaceAll is for regular expressions. '$' is a special character in regular expressions.
If you are not trying to use regular expressions, use String.replace, NOT String.replaceAll.
May be not the best way but a work around,
String parts[] = ss.split("\\$");
Then concat each of them
String output = "";
for(String each:parts){
output=output+each;
}
Then you have your replaced string in output

String split with period (.) shows different Behaviour [duplicate]

This question already has answers here:
How can I use "." as the delimiter with String.split() in java [duplicate]
(8 answers)
Closed 7 years ago.
I was working on String and tried with split() for . like:-
String s = "Hi.Hello";
System.out.println(Arrays.toString(s.split(".")));
The above code outputs [] empty array. But if I escape . like :-
String s = "Hi.Hello";
System.out.println(Arrays.toString(s.split("\\.")));
Its giving correct output as [Hi, Hello].
So I Want To Know:-
Why do i need to escape . but . it is normally not considered a escape character in String as we can use . directly.
The String.split( String ) method takes a regular expression as argument. In a regular expression "." means "any character", so you have to escape it (by adding "\\"), if you actually want to split by "." and not by "any character".
See the api documentation of Pattern for a starter on the regular expressions.
You cannot split it with just . because split()
Splits this string around matches of the given regular expression.
In regex . means 'match any character', so you have to escape it with \\ instead of \ because you also have to escape the \ character!
Small addition to previous answers (which are correct).
It's often better to use StringUtils.split from Apache Commons Lang (javadoc). It takes plain string (instead of regex) as an argument. Also, its behaviour more intuitive:
StringUtils.split("a..b.c", ".") = ["a", "b", "c"]
vs
"a..b.c".split("\\.") = ["a", "", "b", "c"]

| not recognized in java string.split() method [duplicate]

This question already has answers here:
Splitting a Java String by the pipe symbol using split("|")
(7 answers)
Closed 8 years ago.
I am having problems with the java string.split method.
I have a string word like so, which equals- freshness|originality. I then split this string like so:
String words[] = word.split("|");
If I then output words[1], like so:
t1.setText(words[1]);
It gives me the value f. I have worked out that this is the f in the word freshness.
How can I split the string properly so that words[1] is actually originality? Thanks for the help!
You should escape it:
String words[] = word.split("\\|");
Check this explanation in similar question here: Why does String.split need pipe delimiter to be escaped?
String object's split() method has a regular expression as a parameter. That means an unescaped | is not interpreted as a character but as OR and means "empty string OR empty string".
You need to escape the pipe because java recognizes it as a Regular Expression OR Operator.
line.split("\\|")
"|" gets is parsed as "empty string or empty string," which isn't what you are trying to find.
For the record
... ? . + ^ : - $ *
are all Regex Operators and need to be escaped.
You need to escape the character. Use "\\|".
More information on regex escaped characters here.
String test ="freshness|originality";
String[] splits = test.split("\\|");
String part1 = splits[0]; // freshness
String part2 = splits[1]; // originality

Splitting a Java String return empty array? [duplicate]

This question already has answers here:
Split string with dot as delimiter
(13 answers)
Closed 9 years ago.
I have a String something like this
"myValue"."Folder"."FolderCentury";
I want to split from dot("."). I was trying with the below code:
String a = column.replace("\"", "");
String columnArray[] = a.split(".");
But columnArray is coming empty. What I am doing wrong here?
I will want to add one more thing here someone its possible String array object will contain spitted value like mentioned below only two object rather than three.?
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Note that String#split takes a regex.
You need to escape the special char . (That means "any character"):
String columnArray[] = a.split("\\.");
(Escaping a regex is done by \, but in Java, \ is written as \\).
You can also use Pattern#quote:
Returns a literal pattern String for the specified String.
String columnArray[] = a.split(Pattern.quote("."));
By escaping the regex, you tell the compiler to treat the . as the string . and not the special char ..
You must escape the dot.
String columnArray[] = a.split("\\.");
split() accepts an regular expression. So you need to skip '.' to not consider it as a regex meta character.
String[] columnArray = a.split("\\.");
While using special characters need to use the particular escape sequence with it.
'.' is a special character so need to use escape sequence before '.' like:
String columnArray[] = a.split("\\.");
The next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println(Arrays.toString(result));
Produces the required output:
[myValue.Folder, FolderCentury]
The regular Expression tweaks a little with negative look-ahead (this (?!) part), so it will only match the last dot on a String with more than one dot.

Replacing a string with the regular expression ".*" returns the replacement twice [duplicate]

This question already has answers here:
String.replaceAll(regex) makes the same replacement twice
(2 answers)
Closed 9 years ago.
Given this code :
String replaced = "A".replaceAll(".*", "HI");
Why does replaced contain the string HIHI instead of HI as I would have guessed? It seems that it has something to do with the beginning of a line since using the pattern ^.* yields HI, but I don't get the reason for this.
I think this is because .* first matches the entire string, and then matches the empty string at the end of string. Of course, ^.* won't match the empty string at the end of "A", so you end up with only one "HI".
Look at the replaceAll javadoc: Replaces each substring of this string that matches the given regular expression with the given replacement.
This matches two substrings: "" and "A".
You can see this by testing
String replaced = "".replaceAll( ".*", "HI" );
Which results in a single "HI" being being printed
The find method of the Matcher class finds "A" and an empty String after the "A", so there are 2 replacements.
The replaceAll method takes regex and replacement parameter as like (read more) :-
public String replaceAll(String regex,
String replacement)
In this example .* represents the regular expression.
. indicates Any character (may or may not match line terminators)
* indicates zero or more times (Read More regexp)
The output of your given code is right . The regex is matches with * means zero or more times . And it affects the result.
String replaced = "A".replaceAll(".*", "HI");
Output :- HIHI
Hope it will help you.

Categories

Resources