replace or remove special char from List<String> java - java

replace or remove special char from List java
List<String> somestring = ['%french',
'#spanish',
'!latin'];
How to remove the special characters and replace it with space.
List<String> somestring = ['%french',
'#spanish',
'!latin'];
somestring.replaceall('%','');
How to get this as result
List<String> somestring = ['french',
'spanish',
'latin'];

First, never use a raw List. You have a List<String>. Second, a String literal (in Java) is surrounded by double quotes (") not single quotes. Third, you can stream your List<String> and map the elements with a regular expression and collect them back to the original List<String>. Like,
List<String> somestring = Arrays.asList("%french", "#spanish", "!latin");
somestring = somestring.stream().map(s -> s.replaceAll("\\W", ""))
.collect(Collectors.toList());
System.out.println(somestring);
Outputs (as requested)
[french, spanish, latin]

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
private static String REGEX = "\\!|\\%|\\#"; //control on Special characters...
private static String INPUT = "The %dog% says !meow. " + "!All #dogs #say meow.";
private static String REPLACE = ""; //Replacement string
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
//get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
Added a sample snippet to explain the same, please extend to collections accordingly.

Related

Variable used in lambda should be final or effectively final for string appending

Java 8
i have a list of objects: myObjs,
each object has a method to get message.
Now i want to append these messages,
String myStr = new String();
myObjs.forEach( obj -> {
myStr = myStr.join(obj->getMessage());
})
Q1: how to solve: variable used in lambda should be final or effectively final java
Q2: how to separate each message with comma ?
I wrote a simple example program
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Test> list = Arrays.asList(new Test(), new Test(), new Test());
String myStr = list.stream().map(Test::getMessage)
.collect(Collectors.joining(",", "optional prefix", "optional suffix"));
System.out.println(myStr); // output = optional prefixmessage,message,messageoptional suffix
}
}
class Test {
public String getMessage() {
return "message";
}
}
EDIT
If you have a List of Strings you could also do
List<String> stringList = Arrays.asList("a", "b", "c");
System.out.println(String.join(",", stringList));// a,b,c
You can't do this with a String and a lambda (because String is immutable, you can't mutate the reference in a lambda), but you can do this with a collector. Like,
String myStr = myObjs.stream().map(x -> x.getMessage()).collect(Collectors.joining(", "));
or a StringBuilder (but that's messier, and you'd need a check for comma and to manage that joining yourself). I prefer Collectors.joining

multiple replaces in Java

I am using Java 1.8. I have a large amount of text in a buffer. The text has some occurrences likt the following:
"... {NAME} is going to {PLACE}...", blah blah blah.
Then I have two arrays: "{NAME};{PLACE}" and "Mick Jagger;A Gogo", etc. (These are just examples).
I make a Map replacements of these such as
{NAME};Mick Jagger
{PLACE};A Gogo
So I want to do all the replacements. In this case there is only 2 so it is not so cumbersome. Say my original text is in txt:
for (EntrySet<String, String> entry : replacements.entrySet()) {
txt = txt.replace(entry.getKey(), entry.getValue());
}
You can imaging if there are like a lot of replacements this could take a long time.
Is there some better way to make all the replacements, or is this basically what you would do?
To avoid calling String.replace many times, you can use a regex which matches every replacement-key. You can then iteratively scan for the next replacement-key in the input string using a loop, and find its substitute using Map.get:
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ReplaceMap {
private final Pattern p;
public ReplaceMap(Collection<String> keys) {
this.p = Pattern.compile(keys.stream()
.map(ReplaceMap::escapeRegex)
.collect(Collectors.joining("|")));
}
public String replace(String input, Map<String,String> subs) {
Matcher m = p.matcher(input);
StringBuilder out = new StringBuilder();
int i = 0;
while(m.find()) {
out.append(input.substring(i, m.start()));
String key = m.group(0);
out.append(subs.get(key));
i = m.end();
}
out.append(input.substring(i));
return out.toString();
}
// from https://stackoverflow.com/a/25853507/12299000
private static Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
private static String escapeRegex(String s) {
return SPECIAL_REGEX_CHARS.matcher(s).replaceAll("\\\\$0");
}
}
Usage:
> Map<String,String> subs = new HashMap<>();
> subs.put("{NAME}", "Alice");
> subs.put("{PLACE}", "Wonderland");
> ReplaceMap r = new ReplaceMap(subs.keySet());
> r.replace("Hello, {NAME} in {PLACE}.", subs)
"Hello, Alice in Wonderland." (String)
This solution should be about as efficient regardless of how many replacement key/value pairs there are in the subs map.
I'd suggest reading file line by line (using NIO) and for each line you can iterate your map and replace it if you have something. So in this case you need to go over your big data only once

How to convert string array literal to array list with no quotes

Simple scenario but finding difficult to finish off -
my string is -
String ipAdd = "["2.2.2.2","1.1.1.1","6.6.6.6","4.4.4.4"]"
I want to have all elements in an array list. How can I do that?
I try pattern matching for IP and all, not working and by using split function, it includes quotes and bracket.
Using replaceAll() (to remove braces) and split() (to split based on comma) should work :
public static void main(String... args) throws Exception {
String ipAdd = "[\"2.2.2.2\",\"1.1.1.1\",\"6.6.6.6\",\"4.4.4.4\"]";
List<String> list = Arrays.asList(ipAdd.replaceAll("\\[|\\]", "").split(","));
for (String s : list){
System.out.println(s);
}
}
O/P :
"2.2.2.2"
"1.1.1.1"
"6.6.6.6"
"4.4.4.4"
The following code maybe fulfill your requirement:
public static void main(String[] args) {
String st = "[\"2.2.2.2\",\"1.1.1.1\",\"6.6.6.6\",\"4.4.4.4\"]";
String patternString1 = "(\\d\\.\\d\\.\\d\\.\\d)";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(st);
ArrayList<String> list = new ArrayList<>();
while(matcher.find()) {
list.add(matcher.group(1));
}
for (String item : list) {
System.out.println("" + item);
}
}
You can use regular expression with capturing groups to extract the IP from the string. (refer to https://docs.oracle.com/javase/tutorial/essential/regex/groups.html)

java : create string objects using a delimeter

I have input string array containing value like
1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0
What could be the best way to obtain values out of above input which contains 1950/00/00,
1953/00/00, 1958/00/00 , 1960/00/00 and 1962/0 in individual string objects?
Use the method String.split(regex):
String input = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
String[] parts = input.split(";");
for (String part : parts) {
System.out.println(part);
}
The split() method splits the string based on the given regular expression or delimiter, and returns the tokens in the form of array. Below example shows splitting string with (;)
public class MyStrSplit {
public static void main(String a[]){
String str = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
String[] tokens = str.split(";");
for(String s:tokens){
System.out.println(s);
}
}
}
Another choice to split string by regular expression:
public class SpitByRegx
{
public static void main(String[] args)
{
String input = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
Pattern pattern = Pattern.compile("([0-9/]+);?");
Matcher m = pattern.matcher(input);
while(m.find())
{
System.out.println(m.group(1));
}
}
}

Replace Special characters with Character references in string using java

I have a String with special characters which I want to be replaced by corresponding reference.
For example
InputString -> Hi <Nishanth> How &are you !
OutputString -> Hi &ltNishanth&gt How &ampare you &excl
I tried using concept of replace. But I couldn't achieve the desired result ..
I want a function which would do it for me in Java.
replaceAll should be able to do the job just fine.
First, let's make a quick tuple class to represent a pair of Strings: the string to search for and the string to replace that with:
private static class StringTuple{
private String k;
private String v;
public StringTuple(String one, String two){
k = one;
v = two;
}
}
With that, we can build a list of special characters to search for and their corresponding replacements. Note that this list is going to be used in the order that we create it, so it's important that we replace special characters that might show up in other replacements first (such as & or ;).
ArrayList<StringTuple> specialChars = new ArrayList<>();
specialChars.add(new StringTuple("&", "&"));
specialChars.add(new StringTuple("<", "<"));
specialChars.add(new StringTuple(">", ">"));
Finally, we can write a function that loops over the list of special chars and replaces all occurrences with the replacement string:
public static String replaceSpecialChars(String s, ArrayList<StringTuple> specialChars){
for(StringTuple e: specialChars){
s = s.replaceAll(e.k, e.v);
}
return s;
}
Here's a runnable main based off of the above code:
public static void main(String[] args) {
ArrayList<StringTuple> specialChars = new ArrayList<>();
specialChars.add(new StringTuple("&", "&"));
specialChars.add(new StringTuple("<", "<"));
specialChars.add(new StringTuple(">", ">"));
System.out.println(replaceSpecialChars("Hi <Nishanth> How are &you !", specialChars));
}
Output: Hi <Nishanth> How are &you !

Categories