Java: Delimiters and regular expressions - java

I'm using the scanner method to do work on a string and need to filter out junk
here's the sample string
5/31/1948#14:57
I need to strip out the / # :
Theres this doc: http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
But it's really confusing.

You can use the replaceAll method as:
String filetredStr = inputStr.replaceAll("[#/:]","");
And if you want to delete any non-digit you can do:
String filetredStr = inputStr.replaceAll("[^0-9]","");

If you're looking to split it up, use String#split()
String[] parts = "5/31/1948#14:57".split("[/#:]");

Do something like this:-
s.replaceAll("[\\/#:]", "");

An alternative to replaceAll(a,b) is as follows:
String str = "5/31/1948#14:57";
String charsToRemove = "/#:";
for (int i = 0; i < charsToRemove.length(); i++) {
str = str.replace(charsToRemove.charAt(i)+"", "");
}

Related

How to populate with previous value in ; separated string?

I have a string separated by semicolon like this:
"11;21;12;22;13;;14;24;15;25".
Look one value is missing after 13.
I Want to populate that missing number with 13(previous value) and store it into another string.
Try this.
static final Pattern PAT = Pattern.compile("([^;]+)(;;+)");
public static void main(String[] args) {
String input = "11;21;12;22;13;;;14;24;15;25";
String output = PAT.matcher(input)
.replaceAll(m -> (m.group(1) + ";").repeat(m.group(2).length()));
System.out.println(output);
}
output:
11;21;12;22;13;13;13;14;24;15;25
What have you tried so far?
You could solve this problem in many ways i think. If you like to use regular expression, you could do it that way: ([^;]*);;+.
Or you could use a simple String.split(";"); and iterate over the resulting array. Every empty string indicates that there was this ;;
String str = "11;21;12;22;13;;14;24;15;25";
String[] a = str.split(";");
for(int i=0; i<a.length; i++){
if(a[i].length()==0){
System.out.println(a[i-1]);
}
}

Use replaceAll() to replace all occurrences of characters in string

Let's say I have this example string:
String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";
And I want to get this string as a result of a replacement procedure:
String textreplaced = "**/src/pt/data,**/src/pt/groove";
Basically, what I wanted was to replace all occurrences of characters before the /src with **/. This might be tricky and I've tried to capture groups between the comma and the /src text but it doesn't work as I was expecting.
I was using the replaceAll() method (wihtin Jenkins).
Does anyone have any idea how can I get it?
Use positive lookahead:
String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";
System.out.println(text.replaceAll("([\\w/]+)(?=/src)", "**")); // **/src/pt/data,**/src/pt/groove
Here's an alternative non-regex based answer, in case anyone wants it:
String textreplaced = "";
String[] split = text.split(",");
for (int i = 0; i < split.length; i++) {
textreplaced += "**" + split[i].substring(split[i].indexOf("/src"));
if (i != split.length - 1) {
textreplaced += ",";
}
}

Remove domain name from string java

I have a string which looks like this
String str = "domain\ABC";
String str = "domain1\DEF";
How do i write a common function to remove the "domain\" or "domain1\" and just have the string after the the '\'. I tried a couple of different ways but none seem to work.
This is what i have tried.
String[] str = remoteUser.split(remoteUser, '\\');
No need for split() or regex for this, as that is overkill. It's a simple indexOf() operation.
How do i write a common function ... ?
Like this:
public static String removeDomain(String input) {
return input.substring(input.indexOf('/') + 1);
}
The code relies on the fact indexOf() returns -1 if / is not found, so the + 1 will make that 0 and substring(0) then returns input string as-is.
Try it like this.
String str = "domain\\ABC";
String[] split = str.split("\\\\");
//Assign the second element of the array. This only works if you know for sure that there is only one \ in the string.
String withoutSlash = split[1];
Hope it helps.
You might use replaceAll:
System.out.println("domain\\ABC".replaceAll("^.*\\\\",""));
It will replace everything starting at the beginning of the string, until \ symbol.
Try this:
static String getPath(String url) {
int pos = url.indexOf('\');
return pos >= 0 ? url.substring(pos + 1) : url;
}

What is the efficient way to get a specific substring from a string in Java?

I have a string as follows:
"[error=<null>,EntityID=105378032, Context=<null>]"
and i want to extract the EntityID( in this case 105378032), but i want a generalize solution of doing it.
What is the most efficient way of doing it.
I don't want to traverse the string and get that part.
Did you try regex like .*EntityID=(.*?),.* which mean get the group of characters between EntityID= and the next comma , using replaceAll :
String str = "[error=,EntityID=105378032, Context=]";
System.out.println(str.replaceAll(".*EntityID=(.*?),.*", "$1"));// output 105378032
regex demo
Using Regular expressions seems to be the best way out.
This code works:
String str = "[error=,EntityID=105378032, Context=]";
String[] arr = str.split("EntityID="); //splits it on the part "EntityID="
String[] arr1 = arr[1].split(","); // splits it on the next comma in the 'right' half of your string.
System.out.println(arr1[0]); //prints the 'left' half before the comma.
Ideone link here.
Hope this helps!
You can use this method it's work like a charm
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
endString = mainString.substring(startIndex, endIndex);
return endString;
}
Result:
String resultStr = getSubString(yourFullString,",Context","EntityID=");
Happy codding.

How to replace comma (,) with a dot (.) using java

I am having a String str = 12,12
I want to replace the ,(comma) with .(Dot) for decimal number calculation,
Currently i am trying this :
if( str.indexOf(",") != -1 )
{
str.replaceAll(",","\\.");
}
please help
Your problem is not with the match / replacement, but that String is immutable, you need to assign the result:
str = str.replaceAll(",","."); // or "\\.", it doesn't matter...
Just use replace instead of replaceAll (which expects regex):
str = str.replace(",", ".");
or
str = str.replace(',', '.');
(replace takes as input either char or CharSequence, which is an interface implemented by String)
Also note that you should reassign the result
str = str.replace(',', '.')
should do the trick.
if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }
or even better
str = str.replace(',', '.');
Just use str.replace(',', '.') - it is both fast and efficient when a single character is to be replaced. And if the comma doesn't exist, it does nothing.
For the current information you are giving, it will be enought with this simple regex to do the replacement:
str.replaceAll(",", ".");
in the java src you can add a new tool like this:
public static String remplaceVirguleParpoint(String chaine) {
return chaine.replaceAll(",", "\\.");
}
Use this:
String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12
hope help you.
If you want to change it in general because you are from Europe and want to use dots instead of commas for reading an input with a scaner you can do it like this:
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);
System.out.println(sc.locale().getDisplayCountry());
Double accepted with comma instead of dot

Categories

Resources