How can we remove a ':' characters from a string? - java

I have strings like
#lle #mme: #crazy #upallnight:
I would like to remove the words which starts with either # or #. It works perfectly fine if those words doesn't contain the ':' character. However, that ':' character is left whenever I delete the words. Therefore I decided to replace those ':' characters before I delete the words using a string.replace() function. However, they are still not removed.
String example = "#lle #mme: #crazy #upallnight:";
example.replace(':',' ');
The result : #lle #mme: #crazy #upallnight:
I am pretty stuck here, anyhelp would be appreciated.

You can do this:
example = example.replaceAll(" +[##][^ ]+", "");
What this will do is replace any substrings in your string that match the regex pattern [##][^ ]+ with the empty string. Since that pattern matches the words you want to dump, it'll do what you want.
Demo of the pattern on Regex101

From Java docs:
String s = "Abc: abc#:";
String result = s.replace(':',' ');
Output in variable result= Abc abc#
I think you forgot to store the returned result of replace() method in some other String variable.

Related

Printing Strings in Java using replaceAll

I am a beginner in Java. I don't understand how the below code is able to print all the characters in a string:-
System.out.println(yourString.replaceAll(".", "$0\n"));
I have tried reading the documentation on replaceAll and regex, still no clue.
"." is a regular expression which matches any single character. $0 in the replacement string is a placeholder for the full match of the regex. \n is a line break.
Summarized, this snippet replaces each character with itself and adds a line break after the character.
The syntax for replaceAll() method is as follows:
replaceAll(String regex, Stringreplacement) where:
regex : regular expression
replacement : replacement sequence of characters
so when you what to replace a character with \n basically every character will be printed in a different line. For example: yourString = "Hello." =>
output: Hello with every character on a different line
If the String (as you specified) is String yourString = "-"; so the result of System.out.println(yourString.replaceAll(".", "$0\n")); will be "-\n".
Actually, if you need to print all of the String characters why are you using replaceAll? Coz System.out.println(yourString); will do it perfectly.

Using NOT in Regex in replaceAll

I have this string:
String a = "$$bar$55^$$";
I want remove all symbols. I make regex:
String b = a.replaceAll("(?<=[^[\\p{Alpha}][\\p{Digit}]])", "");
But, I get:
$$bar$55^$$
But I want to get this string:
bar55
What am I doing wrong? How can I filter out all characters except letters and numbers?
In Oracle it work for me:
select regexp_replace('$$bar$55^$$','[^[:alpha:][:digit:]]*') from dual;
You are using a lookaround that is a non-consuming pattern, i.e. the match value will always be empty since only a location inside a string will be matched. Use
String b = a.replaceAll("\\P{Alnum}+", "");
The \\P{Alnum}+ pattern matches one or more chars other than ASCII alphanumeric chars. Also, see Predefined Character classes.
Alternatively, you may use
String b = a.replaceAll("[^\\p{L}\\p{P}\\p{S}]+", "");
This will remove chunks of 1 or more chars other than Unicode letters, punctuation and symbols.

String.split() not working as intended

I'm trying to split a string, however, I'm not getting the expected output.
String one = "hello 0xA0xAgoodbye";
String two[] = one.split(" |0xA");
System.out.println(Arrays.toString(two));
Expected output: [hello, goodbye]
What I got: [hello, , , goodbye]
Why is this happening and how can I fix it?
Thanks in advance! ^-^
If you'd like to treat consecutive delimiters as one, you could modify your regex as follows:
"( |0xA)+"
This means "a space or the string "0xA", repeated one or more times".
(\\s|0xA)+ This will match one or more number of space or 0xA in the text and split them
This result is caused by multiple consecutive matches in the string. You may wrap the pattern with a grouping construct and apply a + quantifier to it to match multiple matches:
String one = "hello 0xA0xAgoodbye";
String two[] = one.split("(?:\\s|0xA)+");
System.out.println(Arrays.toString(two));
A (?:\s|0xA)+ regex matches 1 or more whitespace symbols or 0XA literal character sequences.
See the Java online demo.
However, you will still get an empty value as the first item in the resulting array if the 0xA or whitespaces appear at the start of the string. Then, you will have to remove them first:
String two[] = one.replaceFirst("^(?:\\s|0xA)+", "").split("(?:\\s+|0xA)+");
See another Java demo.

Remove unwanted characters from string by regex in Java

I have a string here:
javax.swing.JLabel[,380,30,150x25,alignmentX=0.0,alignmentY=0.0]: Hello
I want to remove everything before the ":", including the ":" itself. This would leave only "Hello". I read about regex, but no combination I tried worked. Can someone tell me how to do it. Thanks in advance!
You need to use replaceAll method or replaceFirst.
string.replaceFirst(".*:\\s*", "");
or
string.replaceAll(".*:\\s*", "");
This would give you only Hello. If you remove \\s* pattern,then it would give you <space>Hello string.
.* Matches any character zero or more times, greedily.
: Upto the colon.
\\s* Matches zero or more space characters.
You could also just split the string by : and take the second string. Like this
String sample = "javax.swing.JLabel[,380,30,150x25,alignmentX=0.0,alignmentY=0.0]: Hello";
System.out.println(sample.split(":", -1)[1]);
This will output
<space>Hello
If you want to get rid of that leading space just trim it off like
System.out.println(sample.split(":", -1)[1].trim());

Regex to replace string with quotes

I need to replace quotes in following string.
String str = "This is 'test()ing' and test()ing'";
Final output should be "This is test()ing and test()ing'";
i.e replace only if it starts with 'test() and ends with '. Text in between remains the same.
This one is not working.
str = str.replaceAll("^('test())(.*)(')$", "test()$2");
Please suggest suitable regex for the same.
This regular expression will have the desired outcome:
str = str.replaceAll("'test\\(\\)(.*?)'", "test()$1");
with .*? the string is matched lazily and doesn't match to the end of the whole string.
You can use:
str = str.replaceAll("'(test\\(\\)[^']*)'", "$1");
RegEx Demo
Doesn't look like you actually want to have the ^ and $ anchors (start/end of line) in your regex.
Aside from that, it will consume more than you want. If you want the .* to stop at the earliest point it can continue, you should make it match reluctantly, like .*?.
So your regex would be:
('test\(\))(.*?)(')
Make the middle part non greedy:
(')(.*?)(')
i.e.
str = str.replaceAll("(')(.*?)(')", "$2");
and if it should always start with test(), add
str = str.replaceAll("(')(test().*?)(')", "$2");
Check this example and this one.

Categories

Resources