Replace value in a regex - java

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

Related

replace last dot in a string with a dollar sign

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

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.

Substring between first instance of two different symbols

I want to parse the following and store it as a new string, with the condition that mawi is stored and everything else is removed.
<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>
One solution I suppose could be a substring starting with the first character after the first > and ending two characters before the first -. All the data is identical. The result is a String with value mawi.
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String substring = initial.substring(example.indexOf(">"));
Not sure where to go from here... Any thoughts?
Although the below code do the trick, I suggest you to use Jsoup or XML Parse if you are processing multiple strings like this
Pattern pattern = Pattern.compile("<ns0:Assignee>(.+?)</ns0:Assignee>");
Matcher matcher = pattern.matcher("<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>");
matcher.find();
String result = matcher.group(1);
String finalString = result.split(" - ")[0];
System.out.println(finalString); // mawi
If all the strings are built like your example string, you could go with this:
initial.substring(initial.indexOf('>') + 1, initial.indexOf(' '));
Note the + 1 at the start index.
When your Strings are more complicated, I would recommend either using a library for working with XML or using Regular Expressions.
So now you got substring which is equal to: >mawi - Manfred Wilson</ns0:Assignee>.
Now, you can substring your substring again to find only mawi, like this;
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String midSub = initial.substring(initial.indexOf('>'));
String finalSub = midSub.substring(1, midSub.indexOf(' ')); // 1 because we still have `>`
System.out.println(finalSub);
Or, one liner:
String finalSub = initial.substring(initial.indexOf('>')+1, initial.indexOf(' '));
show this:
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(s.indexOf("<ns0:Assignee>")+"<ns0:Assignee>".length(), s.indexOf("</ns0:Assignee>"));
public class string {
public static void main(String[] args) {
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(14, 18);
System.out.println(s);
}
}

Need regular expression help for stripping the string from format xxxxxx/x/xxxxx/xxx

Hi there is a requirement to strip a string along backslash(/)
For example I have
String vret = "Comment Four/Y/34147/D_Z";
This has to be splitted into 4 string namely
Str sarr[]={comment,Y,34147,D_Z}
The string will be always in this format only like XXXXX/X/XXXXXX/XXX:
the first part will be alphanumeric value,
the second part is single character
the third is always a number
the fourth is any character
I am assuming there will be regex to do this kind of operations in java
What about
String[] sarr = vret.split("/");
Oracle even has the documentation.
using full regex and pre-compiled pattern
Pattern p = Pattern.compile("([\\w]+)/(\\w)/(\\d+)/(\\.*)");
Matcher m = p.matcher(vret);
if(m.matches()){
String first = m.group(1);
String second= m.group(2);
int third = Integer.parseInt(m.group(3));
String fourth= m.group(4);
}
String sarr[] = vret.split("/");
Simple, uh ?

Regarding String manipulation

I have a String str which can have list of values like below. I want the first letter in the string to be uppercase and if underscore appears in the string then i need to remove it and need to make the letter after it as upper case. The rest all letter i want it to be lower case.
""
"abc"
"abc_def"
"Abc_def_Ghi12_abd"
"abc__de"
"_"
Output:
""
"Abc"
"AbcDef"
"AbcDefGhi12Abd"
"AbcDe"
""
Well, without showing us that you put any effort into this problem this is going to be kinda vague.
I see two possibilities here:
Split the string at underscores, apply the answer from this question to each part and re-combine them.
Create a StringBuilder, walk through the string and keep track of whether you are
at the start of the string
after an underscore or
somewhere else
and act appropriately on the current character before appending it to the StringBuilder instance.
replace _ with space (str.replace("_", " "))
use WordUtils.capitalizeFully(str); (from commons-lang)
replace space with nothing (str.replace(" ", ""))
You can use following regexp based code:
public static String camelize(String input) {
char[] c = input.toCharArray();
Pattern pattern = Pattern.compile(".*_([a-z]).*");
Matcher m = pattern.matcher(input);
while ( m.find() ) {
int index = m.start(1);
c[index] = String.valueOf(c[index]).toUpperCase().charAt(0);
}
return String.valueOf(c).replace("_", "");
}
Use Pattern/Matcher in the java.util.regex package:
for each string that is in your array do the following:
StringBuffer output = new StringBuffer();
Matcher match = Pattern.compile("[^|_](\w)").matcher(inStr);
while(match.find()) {
match.appendReplacement(output, matcher.match(0).ToUpper());
}
match.appendTail(output);
// Will have the properly capitalized string.
String capitalized = output.ToString();
The regular expression looks for either the start of the string or an underscore "[^|_]"
Then puts the following character into a group "(\w)"
The code then goes through each of the matches in the input string capitalizing the first satisfying group.

Categories

Resources