replace last dot in a string with a dollar sign - java

I would like to replace the last dot in the following string with a dollar sign, how can I do that?
de.java_chess.javaChess.game.GameImpl.GameStatus
I would like to have de.java_chess.javaChess.game.GameImpl$GameStatus instead.
I am using the following line of code to do so:
invokedMeth = invokedMeth.replaceAll("(.*)\\.(\\d+)$","$1$$2");
However, this doesn't work and I end up with the same original string that I had as an input. How can I fix this?

For this requirement, I would use a non-regex solution that can be easier to understand as well as more efficient.
StringBuilder invokedMethSb = new StringBuilder(invokedMeth);
invokedMethSb.setCharAt(invokedMethSb.lastIndexOf("."), '$');
invokedMeth = invokedMethSb.toString();
/*de.java_chess.javaChess.game.GameImpl$GameStatus*/
StringBuilder has some good utils for these operations, such as setCharAt.
As a personal opinion, I prefer the following one:
char[] invokedArray = invokedMeth.toCharArray();
invokedArray[invokedMeth.lastIndexOf(".")]='$';
invokedMeth = new String(invokedArray);
/*de.java_chess.javaChess.game.GameImpl$GameStatus*/
Regex solution:
You can use the Positive Lookahead, (?=([^.]*)$) where ([^.]*) matches any number of non-dot (i.e. [^.]) character and $ asserts position at the end of a line. You can check regex101.com for more explanation.
public class Main {
public static void main(String[] args) {
String str = "de.java_chess.javaChess.game.GameImpl.GameStatus";
str = str.replaceAll("\\.(?=([^.]*)$)", "\\$");
System.out.println(str);
}
}
Output:
de.java_chess.javaChess.game.GameImpl$GameStatus

A proper regular expression can also help with this replacement:
String withDot = "de.java_chess.javaChess.game.GameImpl.GameStatus";
String with$ = withDot.replaceFirst("(\\w+(\\.\\w+)*)(\\.(\\w+))", "$1\\$$4");
System.out.println(with$);
Output online demo:
de.java_chess.javaChess.game.GameImpl$GameStatus

Related

Replace value in a regex

I have the next String in java:
|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|
So I need to replace the value |50200| (second one) with other value according to some decisions,but only need to replace the second one, how can I do, since replace or replaceAll don't work in this case. I was trying with some regex and appendReplacement but it did not work,also I need it to be as quick as possible, code below:
String event = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
Pattern p = Pattern.compile("^\|(\w*)\|(\d+)\|(\d+(\.\d{1,})*)\|(\d+(\.\d{1,})*)\|(\d+(\.\d{1,})*)\|\w+\|\w+\|\d{14}\|$");
Matcher mat = p.matcher(event);
StringBuffer aux = new StringBuffer();
mat.appendReplacement(aux, mat.group(5));
String newString = aux.toString();
But the value of newString is 50200, so basically I want to replace it with 12345, so the String would look like this |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
Thanks in advance for your help
The thing is I have to use the regex to check the format of the String before doing the replace, because there could be other String with different formats
You can use indexOf to find the second position, then substring around the value you want to replace.
For example
public static void main(String[] args) {
String s = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
String find = "50200";
String replace = "12345";
int firstOccur = s.indexOf(find);
int secondOccur = s.indexOf(find, firstOccur+find.length());
StringBuilder sb = new StringBuilder(s.substring(0, secondOccur));
sb.append(replace);
sb.append(s.substring(secondOccur+find.length()));
System.out.println(sb.toString());
// |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
}
Since question has been tagged as regex and non-regex solution is possible but a bit longish here is a simple one line regex solution:
String data = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
String srch = "|50200|";
String repl = "|12345|";
String rdata = data.replaceFirst("^(.*?(\\|50200\\|).*?)\\2", "$1|12345|");
//=> |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
Regex ^(.*?(\|50200\|).*?)\2 finds 2nd instance of |50200| and captures everything before 2nd instance into captured group #1. We use backreference $1 in replacement to put that captured text back.
RegEx Demo

How can i find whether the string starts with 's','r','p' in java

Example: This is my string,
String sample = "s5656";
If the first character of the string contains 's' or 'p' or 'r' means i should remove the character,Otherwise i have to
return the original string.
Is there any optimized way to do that like "regex" or "StringUtils" in apache common?
Why do you want to add 3rd party jar for this kind of simple requirement? You can try as follows
String sample = "s5656";
if(sample.startsWith("s")||sample.startsWith("r")||sample.startsWith("p")){
// do necessary
}else{
// do necessary
}
String#startsWith()
A simple regex could solve your problem :
public static void main(String[] args) {
String s = "s5656s";
System.out.println(s.replaceFirst("^[spr]", "")); // a String which begins with s,p or r
}
O/P:
5656s
PS: regex here leads to smaller/simpler but inefficient code. Use Ruchira's answer for a rather long but efficient code. :)
^(s|p|r)
Try this.Use yourString.replaceAll() / replaceFirst() with empty string.Use m.
See demo.
http://regex101.com/r/dZ1vT6/49
I should go for replaceAll function with multiline modifier (?m).
String s = "s5656s\n" +
"r878dsjhj\n" +
"fshghg";
System.out.println(s.replaceAll("(?m)^[spr]", ""));
Output:
5656s
878dsjhj
fshghg

Java using regex to verify an input string

g.:
String string="Marc Louie, Garduque Bautista";
I want to check if a string contains only words, a comma and spaces. i have tried to use regex and the closest I got is this :
String pattern = "[a-zA-Z]+(\\s[a-zA-Z]+)+";
but it doesnt check if there is a comma in there or not. Any suggestion ?
You need to use the pattern
^[A-Za-z, ]++$
For example
public static void main(String[] args) throws IOException {
final String input = "Marc Louie, Garduque Bautista";
final Pattern pattern = Pattern.compile("^[A-Za-z, ]++$");
if (!pattern.matcher(input).matches()) {
throw new IllegalArgumentException("Invalid String");
}
}
EDIT
As per Michael's astute comment the OP might mean a single comma, in which case
^[A-Za-z ]++,[A-Za-z ]++$
Ought to work.
Why not just simply:
"[a-zA-Z\\s,]+"
Use this will best
"(?i)[a-z,\\s]+"
If you mean "some words, any spaces and one single comma, wherever it occurs to be" then my feeling is to suggest this approach:
"^[^,]* *, *[^,]*$"
This means "Start with zero or more characters which are NOT (^) a comma, then you could find zero or more spaces, then a comma, then again zero or more spaces, then finally again zero or more characters which are NOT (^) a comma".
To validate String in java where No special char at beginning and end but may have some special char in between.
String strRGEX = "^[a-zA-Z0-9]+([a-zA-Z0-9-/?:.,\'+_\\s])+([a-zA-Z0-9])$";
String toBeTested= "TesADAD2-3t?S+s/fs:fds'f.324,ffs";
boolean testResult= Pattern.matches(strRGEX, toBeTested);
System.out.println("Test="+testResult);

Java, replace string numbers with blankstring and remove everything after the numbers

I have strings like:
Alian 12WE
and
ANI1451
Is there any way to replace all the numbers (and everything after the numbers) with an empty string in JAVA?
I want the output to look like this:
Alian
ANI
With a regex, it's pretty simple:
public class Test {
public static String replaceAll(String string) {
return string.replaceAll("\\d+.*", "");
}
public static void main(String[] args) {
System.out.println(replaceAll("Alian 12WE"));
System.out.println(replaceAll("ANI1451"));
}
}
You could use a regex to remove everyting after a digit is found - something like:
String s = "Alian 12WE";
s = s.replaceAll("\\d+.*", "");
\\d+ finds one or more consecutive digits
.* matches any characters after the digits
Use Regex
"Alian 12WE".split("\\d")[0] // Splits the string at numbers, get the first part.
Or replace "\\d.+$" with ""

Java- Extract part of a string between two special characters

I have been trying to figure out how to extract a portion of a string between two special characters ' and " I've been looking into regex, but frankly I cannot understand it.
Example in Java code:
String str="21*90'89\"";
I would like to pull out 89
In general I would just like to know how to extract part of a string between two specific characters please.
Also it would be nice to know how to extract part of the string from the beginning to a specific character like to get 21.
Try this regular expression:
'(.*?)"
As a Java string literal you will have to write it as follows:
"'(.*?)\""
Here is a more complete example demonstrating how to use this regular expression with a Matcher:
Pattern pattern = Pattern.compile("'(.*?)\"");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
See it working online: ideone
If you'll always have a string like that (with 3 parts) then this is enough:
String str= "21*90'89\"";
String between = str.split("\"|'")[1];
Another option, if you can assure that your strings will always be in the format you provide, you can use a quick-and-dirty substring/indexOf solution:
str.substring(str.indexOf("'") + 1, str.indexOf("\""));
And to get the second piece of data you asked for:
str.substring(0, str.indexOf("*"));
public static void main(final String[] args) {
final String str = "21*90'89\"";
final Pattern pattern = Pattern.compile("[\\*'\"]");
final String[] result = pattern.split(str);
System.out.println(Arrays.toString(result));
}
Is what you are looking for... The program described above produces:
[21, 90, 89]
I'm missing the simplest possible solution here:
str.replaceFirst(".*'(.*)\".*", "$1");
This solution is by far the shortest, however it has some drawbacks:
In case the string looks different, you get the whole string back without warning.
It's not very efficient, as the used regex gets compiled for each use.
I wouldn't use it except as a quick hack or if I could be really sure about the input format.
String str="abc#defg#lmn!tp?pqr*tsd";
String special="!?##$%^&*()/<>{}[]:;'`~";
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=0;i<str.length();i++)
{
for(int j=0;j<special.length();j++)
if(str.charAt(i)==special.charAt(j))
al.add(i);
}
for(int i=0;i<al.size()-1;i++)
{
int start=al.get(i);
int end=al.get(i+1);
for(int j=start+1;j<end;j++)
System.out.print(str.charAt(j));
System.out.print(" ");
}
String str= 21*90'89;
String part= str.split("[*|']");
System.out.println(part[0] +""+part[1]);

Categories

Resources