How to replace special Character with a String replacer - java

I have the following Code:
#Test
public void testReplace(){
int asciiVal = 233;
String str = new Character((char) asciiVal).toString();
String oldName = "Fr" + str + "d" + str + "ric";
System.out.println(oldName);
String newName = oldName.replace("é", "_");
System.out.println(newName);
Assert.assertNotEquals(oldName, newName); // Its still equal. Howto Replace with a String
String notTheWayILike = oldName.replace((char) 233 + "", "_"); // I don't want to do this.
Assert.assertNotEquals(oldName, notTheWayILike);
}
How can I replace the character with a String ?
I need this, because they should be userfriendly defined as Strings or chars.

Related

Split filename into groups

Input:
"MyPrefix_CH-DE_ProductName.pdf"
Desired output:
["MyPrefix", "CH", "DE", "ProductName"]
CH is a country code, and it should come from a predefined list, eg. ["CH", "IT", "FR", "GB"]
Edit: prefix can contain _ and - as well but not CH or DE.
DE is a language code, and it should come from a predefined list, eg. ["EN", "IT", "FR", "DE"]
How do I do that?
I'm looking for a regex based solution here.
I'll assume that the extension is always pdf
String str = "MyPref_ix__CH-DE_ProductName.pdf";
String regex = "(.*)_(CH|IT|FR|GB)-(EN|IT|FR|DE)_(.*)\\.pdf";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
String[] res = new String[4];
if(matcher.matches()) {
res[0] = matcher.group(1);
res[1] = matcher.group(2);
res[2] = matcher.group(3);
res[3] = matcher.group(4);
}
You can try the following
String input = "MyPrefix_CH-DE_ProductName.pdf";
String[] segments = input.split("_");
String prefix = segments[0];
String countryCode = segments[1].split("-")[0];
String languageCode = segments[1].split("-")[1];
String fileName = segments[2].substring(0, segments[2].length() - 4);
System.out.println("prefix " + prefix);
System.out.println("countryCode " + countryCode);
System.out.println("languageCode " + languageCode);
System.out.println("fileName " + fileName);
this code does the split and create an object using the returned result, more OOP.
package com.local;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
List<String> countries = Arrays.asList("CH", "IT", "FR", "GB");
List<String> languages = Arrays.asList("EN", "IT", "FR", "DE");
String filename = "MyPrefix_CH-DE_ProductName.pdf";
//Remove prefix
filename = filename.split("\\.")[0];
List<String> result = Arrays.asList(filename.split("[_\\-]"));
FileNameSplitResult resultOne = new FileNameSplitResult(result.get(0), result.get(1), result.get(2), result.get(3));
System.out.println(resultOne);
}
static class FileNameSplitResult{
String prefix;
String country;
String language;
String productName;
public FileNameSplitResult(String prefix, String country, String language, String productName) {
this.prefix = prefix;
this.country = country;
this.language = language;
this.productName = productName;
}
#Override
public String toString() {
return "FileNameSplitResult{" +
"prefix='" + prefix + '\'' +
", country='" + country + '\'' +
", language='" + language + '\'' +
", productName='" + productName + '\'' +
'}';
}
}
}
Result of execution:
FileNameSplitResult{prefix='MyPrefix', country='CH', language='DE', productName='ProductName'}
You can use String.split two times so you can first split by '_' to get the CH-DE string and then split by '-' to get the CountryCode and LanguageCode.
Updated after your edit, with input containing '_' and '-':
The following code scans through the input String to find countries matches. I changed the input to "My-Pre_fix_CH-DE_ProductName.pdf"
Check the following code:
public static void main(String[] args) {
String [] countries = {"CH", "IT", "FR", "GB"};
String input = "My-Pre_fix_CH-DE_ProductName.pdf";
//First scan to find country position
int index = -1;
for (int i=0; i<input.length()-4; i++){
for (String country:countries){
String match = "_" + country + "-";
String toMatch = input.substring(i, match.length()+i);
if (match.equals(toMatch)){
//Found index
index=i;
break;
}
}
}
String prefix = input.substring(0,index);
String remaining = input.substring(index+1);//remaining is CH-DE_ProductName.pdf
String [] countryLanguageProductCode = remaining.split("_");
String country = countryLanguageProductCode[0].split("-")[0];
String language = countryLanguageProductCode[0].split("-")[1];
String productName = countryLanguageProductCode[1].split("\\.")[0];
System.out.println("[\"" + prefix +"\", \"" + country + "\", \"" + language +"\", \"" + productName+"\"]");
}
It outputs:
["My-Pre_fix", "CH", "DE", "ProductName"]
You can use the following regex :
^(.*?)_(CH|IT|FR|GB)-(EN|IT|FR|DE)_(.*)$
Java code :
Pattern p = Pattern.compile("^(.*?)_(CH|IT|FR|GB)-(EN|IT|FR|DE)_(.*)$");
Matcher m = p.matcher(input);
if (m.matches()) {
String[] result = { m.group(1), m.group(2), m.group(3), m.group(4) };
}
You can try it here.
Note that it would still fail if the prefix could contain a substring like _CH-EN_, and I don't think there's much than can be done about it beside sanitize the inputs.
One more alternative, which is pretty much the same as #billal GHILAS and #Aaron answers but using named groups. I find it handy for myself or for others who after a while look at my code immediately see what my regex does. The named groups make it easier.
String str = "My_Prefix_CH-DE_ProductName.pdf";
Pattern filePattern = Pattern.compile("(?<prefix>\\w+)_"
+ "(?<country>CH|IT|FR|GB)-"
+ "(?<language>EN|IT|FR|DE)_"
+ "(?<product>\\w+)\\.");
Matcher file = filePattern.matcher(str);
file.find();
System.out.println("Prefix: " + file.group("prefix"));
System.out.println("Country: " + file.group("country"));
System.out.println("Language: " + file.group("language"));
System.out.println("Product: " + file.group("product"));

Split and extract java string multiple times

I have a string in java e.g:
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups] ANOTHERVAR(balloons{clowns} bubbles)"
The string contains variables for which i need to extract information out of. What i am looking for end result is something like this:
String myVar = "(some data[some text])"
String someVar = "(table spoon fork(chairs cloths)[cups]"
String anotherVar = "(balloons{clowns} bubbles)"
The string may also be like:
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups]"
And result should be:
String myVar = "(some data[some text])"
String someVar = "(table spoon fork(chairs cloths)[cups]"
String anotherVar = ""
I have tried:
String[] parts = string.split("MYVAR1");
But that gets me everything and not just the MYVAR1 contents.
try this
public class TestClass {
public static void main(String a[]){
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups] ANOTHERVAR(balloons{clowns} bubbles)";
System.out.println("myVar = " + getValue(myString, "MYVAR1", "SOMEVAR"));
System.out.println("someVar = " + getValue(myString, "SOMEVAR", "ANOTHERVAR"));
System.out.println("anotherVar = "+ getValue(myString, "ANOTHERVAR", null));
System.out.println();
myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups]";
System.out.println("myVar = " + getValue(myString, "MYVAR1", "SOMEVAR"));
System.out.println("someVar = " + getValue(myString, "SOMEVAR", "ANOTHERVAR"));
System.out.println("anotherVar = " + getValue(myString, "ANOTHERVAR", null));
}
private static String getValue(String myString, String name,String nextName){
if(myString == null || name == null) return "";
int a = myString.indexOf(name);
if (a == -1) return "";
if(nextName == null){
return myString.substring(a+name.length());
}
else {
int b = myString.indexOf(nextName);
if(b>-1){
return myString.substring(a + name.length(), b);
}
else {
return myString.substring(a + name.length());
}
}
}
}
Try below code :
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups] ANOTHERVAR(balloons{clowns} bubbles)";
String myVar1 = myString.split("MYVAR1")[1].split("SOMEVAR")[0];
String tmpSomeVAR = myString.split("SOMEVAR")[1];
String someVar = "";
String ANOTHERVAR = "";
String[] tmp = tmpSomeVAR.split("ANOTHERVAR");
if (tmpSomeVAR.split("ANOTHERVAR").length == 1) {
someVar = tmpSomeVAR;
} else {
String[] parts = tmpSomeVAR.split("ANOTHERVAR");
someVar = parts[0];
ANOTHERVAR = parts[1];
}
System.out.println(myVar1);
System.out.println(someVar);
System.out.println(ANOTHERVAR);
From what I understood, your trying to extract words within brackets.
You can use regular expression to match what you need.
For example:
String regex = “\\(.+\\)(\\[.+\\]){0,1}” // this match everything inside the brackets and match what’s inside [] when present

Extracting a value from a file name base on regex in Java

Suppose my file name pattern is something like this %#_Report_%$_for_%&.xls and %# and %$ regex can have any character but %& is a date.
Now how can i get the actual values of those regex on filename in java.
For example if actual filename is Genr_Report_123_for_20151105.xls how to get
%# value is Genr
%$ value is 123
%& value is 20151105
You can do it like this:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Rgx {
private String str1 = "", str2 = "", date = "";
public static void main(String[] args) {
String fileName = "Genr_Report_123_for_20151105.xls";
Rgx rgx = new Rgx();
rgx.extractValues(fileName);
System.out.println(rgx.str1 + " " + rgx.str2 + " " + rgx.date);
}
private void extractValues(String fileName) {
Pattern pat = Pattern.compile("([^_]+)_Report_([^_]+)_for_([\\d]+)\\.xls");
Matcher m = pat.matcher(fileName);
if (m.find()) {
str1 = m.group(1);
str2 = m.group(2);
date = m.group(3);
}
}
}

Split mathematical string in Java

I have this string: "23+43*435/675-23". How can I split it? The last result which I want is:
String 1st=23
String 2nd=435
String 3rd=675
String 4th=23
I already used this method:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = s.split("\\-");
String[] split2 = s.split("\\*");
String[] split3 = s.split("\\/");
String plus = split[1];
String minus = split1[1];
String multi = split2[1];
String div = split3[1];
System.out.println(plus+"\n"+minus+"\n"+multi+"\n"+div+"\n");
But it gives me this result:
pLus-minuss*multi/divide
minuss*multi/divide
multi/divide
divide
But I require result in this form
pLus
minuss
multi
divide
Try this:
public static void main(String[] args) {
String s ="23+43*435/675-23";
String[] ss = s.split("[-+*/]");
for(String str: ss)
System.out.println(str);
}
Output:
23
43
435
675
23
I dont know why you want to store in variables and then print . Anyway try below code:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String first =ss[1];
String second =ss[2];
String third =ss[3];
String forth =ss[4];
System.out.println(first+"\n"+second+"\n"+third+"\n"+forth+"\n");
}
Output:
pLus
minuss
multi
divide
Try this out :
String data = "23+43*435/675-23";
Pattern pattern = Pattern.compile("[^\\+\\*\\/\\-]+");
Matcher matcher = pattern.matcher(data);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
for (int index = 0; index < list.size(); index++) {
System.out.println(index + " : " + list.get(index));
}
Output :
0 : 23
1 : 43
2 : 435
3 : 675
4 : 23
I think it is only the issue of index. You should have used index 0 to get the split result.
String[] split = s.split("\\+");
String[] split1 = split .split("\\-");
String[] split2 = split1 .split("\\*");
String[] split3 = split2 .split("\\/");
String hello= split[0];//split[0]=hello,split[1]=pLus-minuss*multi/divide
String plus= split1[0];//split1[0]=plus,split1[1]=minuss*multi/divide
String minus= split2[0];//split2[0]=minuss,split2[1]=multi/divide
String multi= split3[0];//split3[0]=multi,split3[1]=divide
String div= split3[1];
If the order of operators matters, change your code to this:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = split[1].split("\\-");
String[] split2 = split1[1].split("\\*");
String[] split3 = split2[1].split("\\/");
String plus = split1[0];
String minus = split2[0];
String multi = split3[0];
String div = split3[1];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
Otherwise, to spit on any operator, and store to variable do this:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String plus = ss[1];
String minus = ss[2];
String multi = ss[3];
String div = ss[4];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
}

replaceAll is not replacing the substrings

When I run my code after I input this
1 qwertyuiopasdfghjklzxcvbnm
will
it still prints out will instead of replacing the characters like it should, why is that?
public static void main(String[] args)
{
String input="";
int cases= sc.nextInt();
String al= sc.next();
String upAl= al.toUpperCase();
char [] upAlph = upAl.toCharArray();
char[] alph = al.toCharArray();
for(int i=0; i<cases; i++)
{
input=sc.next();
input.replaceAll("a", ""+ alph[0]);
input.replaceAll("b", ""+ alph[1]);
input.replaceAll("c", ""+ alph[2]);
input.replaceAll("d", ""+ alph[3]);
input.replaceAll("e", ""+ alph[4]);
input.replaceAll("f", ""+ alph[5]);
input.replaceAll("g", ""+ alph[6]);
input.replaceAll("h", ""+ alph[7]);
input.replaceAll("i", ""+ alph[8]);
input.replaceAll("j", ""+ alph[9]);
input.replaceAll("k", ""+ alph[10]);
input.replaceAll("l", ""+ alph[11]);
input.replaceAll("m", ""+ alph[12]);
input.replaceAll("n", ""+ alph[13]);
input.replaceAll("o", ""+ alph[14]);
input.replaceAll("p", ""+ alph[15]);
input.replaceAll("q", ""+ alph[16]);
input.replaceAll("r", ""+ alph[17]);
input.replaceAll("s", ""+ alph[18]);
input.replaceAll("t", ""+ alph[19]);
input.replaceAll("u", ""+ alph[20]);
input.replaceAll("v", ""+ alph[21]);
input.replaceAll("w", ""+ alph[22]);
input.replaceAll("x", ""+ alph[23]);
input.replaceAll("y", ""+ alph[24]);
input.replaceAll("z", ""+ alph[25]);
input.replaceAll("A", upAlph[0]+"");
input.replaceAll("B", upAlph[1]+"");
input.replaceAll("C", upAlph[2]+"");
input.replaceAll("D", upAlph[3]+"");
input.replaceAll("E", upAlph[4]+"");
input.replaceAll("F", upAlph[5]+"");
input.replaceAll("G", upAlph[6]+"");
input.replaceAll("H", upAlph[7]+"");
input.replaceAll("I", upAlph[8]+"");
input.replaceAll("J", upAlph[9]+"");
input.replaceAll("K", upAlph[10]+"");
input.replaceAll("L", upAlph[11]+"");
input.replaceAll("M", upAlph[12]+"");
input.replaceAll("N", upAlph[13]+"");
input.replaceAll("O", upAlph[14]+"");
input.replaceAll("P", upAlph[15]+"");
input.replaceAll("Q", upAlph[16]+"");
input.replaceAll("R", upAlph[17]+"");
input.replaceAll("S", upAlph[18]+"");
input.replaceAll("T", upAlph[19]+"");
input.replaceAll("U", upAlph[20]+"");
input.replaceAll("V", upAlph[21]+"");
input.replaceAll("W", upAlph[22]+"");
input.replaceAll("X", upAlph[23]+"");
input.replaceAll("Y", upAlph[24]+"");
input.replaceAll("Z", upAlph[25]+"");
input.replaceAll("_", " ");
pw.println(input);
}
Strings are immutable. Assign input to the result of replaceAll:
input = input.replaceAll("a", ""+ alph[0]);
...
Aside: Consider using String#replace if regular expressions are not required.
Strings are immutable in java , you cannot modify strings after creating them, consider assigning the result of replaceAll to the original string
input = input.replaceAll("string", "string");
The method replaceAll returns a new string after replacement.
even += doesn't add the value to the string, it creates another string internally.Thus, consider using StringBuilder for better performance if you want to modify the string very often
I was coding this method by Friday, before leaving from job, but had to leave.
Anyhow, I did finish it today.
public static String replaceStringChars(String input, String abc, String replacement, boolean ignoreCase) {
abc = (ignoreCase ? abc.toLowerCase() : abc) + (ignoreCase ? abc.toUpperCase() : "") + "_";
replacement = (ignoreCase ? replacement.toLowerCase() : replacement) + (ignoreCase ? replacement.toUpperCase() : "") + " ";
input = input.replace(abc, replacement);
StringBuilder newString = new StringBuilder(input);
for (int a = 0; a < input.length(); a++) {
char chr = input.charAt(a);
int index = abc.indexOf(chr);
if (index >= 0) {
newString.setCharAt(a, replacement.charAt(index));
}
}
return newString.toString();
}
How to test it? :
public static void main(String [] args)
{
String input = "will_is_my_pastor";
String abc = "abcdefghijklmnopqrstuvwxyz";
String replacement = "qwertyuiopasdfghjklzxcvbnm";
System.out.println(abc);
System.out.println(replacement);
System.out.println(replaceStringChars(input, abc, replacement, true));
}

Categories

Resources