Dynamic incrementation of all numbers within a String [duplicate] - java

This question already has answers here:
How to increment string variable? [closed]
(4 answers)
Closed 6 years ago.
Is there any Java solution of replacing a digit in a String other than getting the digit using a matcher, increment it by one and replace it?
"REPEAT_FOR_4" will return "REPEAT_FOR_5"
"REPEAT_FOR_10" will return "REPEAT_FOR_11"
I would like to do it in one line with regex and replace, not by recomposing the String as "REPEAT_FOR_" and add the number after incrementation.
Thank you!
Later edit: I would like to know how to replace a number with the following one in a String.

I didn't use regex but here is the solution in one line. Considering your string remains the same.
public String getIncrementedString (String str){
return ("REPEAT_FOR_" + (Character.getNumericValue(str.charAt(11))+1));
}

Yes of course it's possible. using regex Pattern and Matcher, here's what you will need to do:
String str = "REPEAT_FOR_4";
Pattern p = Pattern.compile("([0-9]+)");
Matcher m = p.matcher(str);
StringBuffer s = new StringBuffer();
while (m.find())
m.appendReplacement(s, String.valueOf(1+ Integer.parseInt(m.group(1))));
String updated = s.toString();
System.out.println(updated);
This is a working Example that returns REPEAT_FOR_5 as output.

You can try this.
String ss = "REPEAT_FOR_4";
int vd = Integer.valueOf(ss.substring(ss.length() - 1));
String nss = ss.replaceAll("\\d",String.valueOf(vd+1));
System.out.println(nss);
output:
REPEAT_FOR_5
with regex: if the digit is not at the end of the string.
String ss = "REPEAT_5_FOR_ME";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(ss);
m.find();
String strb = m.group();
int vd = Integer.valueOf(strb);
String nss = ss.replaceAll("\\d",String.valueOf(vd+1));
System.out.println(nss);
output:
REPEAT_6_FOR_ME
Base on the issue raised in the comments comments i think this solution with regex will help.
public static String convStr(String str){
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
m.find();
String strb = m.group();
int vd = Integer.valueOf(strb);
return str.replaceAll("\\d",String.valueOf(vd+1));
}

Related

JAVA Get text from String

Hi I get this String from server :
id_not="autoincrement"; id_obj="-"; id_tr="-"; id_pgo="-"; typ_not=""; tresc="Nie wystawił"; datetime="-"; lon="-"; lat="-";
I need to create a new String e.x String word and send a value which I get from String tresc="Nie wystawił"
Like #Jan suggest in comment you can use regex for example :
String str = "id_not=\"autoincrement\"; id_obj=\"-\"; id_tr=\"-\"; id_pgo=\"-\"; typ_not=\"\"; tresc=\"Nie wystawił\"; datetime=\"-\"; lon=\"-\"; lat=\"-\";";
Pattern p = Pattern.compile("tresc(.*?);");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group());
}
Output
tresc="Nie wystawił";
If you want to get only the value of tresc you can use :
Pattern p = Pattern.compile("tresc=\"(.*?)\";");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1));
}
Output
Nie wystawił
Something along the lines of
Pattern p = Pattern.compile("tresc=\"([^\"]+)\");
Matcher m = p.matcher(stringFromServer);
if(m.find()) {
String whatYouWereLookingfor = m.group(1);
}
should to the trick. JSON parsing might be much better in the long run if you need additional values
Your question is unclear but i think you get a string from server and from that string you want the string/value for tresc. You can first search for tresc in the string you get. like:
serverString.substring(serverString.indexOf("tresc") + x , serverString.length());
Here replace x with 'how much further you want to pick characters.
Read on substring and delimiters
As values are separated by semicolon so annother solution could be:
int delimiter = serverstring.indexOf(";");
//in string thus giving you the index of where it is in the string
// Now delimiter can be -1, if lets say the string had no ";" at all in it i.e. no ";" is not found.
//check and account for it.
if (delimiter != -1)
String subString= serverstring.substring(5 , iend);
Here 5 means tresc is on number five in string, so it will five you tresc part.
You can then use it anyway you want.

Parse string value from URL

I have a string (which is an URL) in this pattern https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg
now I want to clip it to this
media/93939393hhs8.jpeg
I want to remove all the characters before the second last slash /.
i'm a newbie in java but in swift (iOS) this is how we do this:
if let url = NSURL(string:"https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg"), pathComponents = url.pathComponents {
let trimmedString = pathComponents.suffix(2).joinWithSeparator("/")
print(trimmedString) // "output = media/93939393hhs8.jpeg"
}
Basically, I'm removing everything from this Url expect of last 2 item and then.
I'm joining those 2 items using /.
String ret = url.substring(url.indexof("media"),url.indexof("jpg"))
Are you familiar with Regex? Try to use this Regex (explained in the link) that captures the last 2 items separated with /:
.*?\/([^\/]+?\/[^\/]+?$)
Here is the example in Java (don't forget the escaping with \\:
Pattern p = Pattern.compile("^.*?\\/([^\\/]+?\\/[^\\/]+?$)");
Matcher m = p.matcher(string);
if (m.find()) {
System.out.println(m.group(1));
}
Alternatively there is the split(..) function, however I recommend you the way above. (Finally concatenate separated strings correctly with StringBuilder).
String part[] = string.split("/");
int l = part.length;
StringBuilder sb = new StringBuilder();
String result = sb.append(part[l-2]).append("/").append(part[l-1]).toString();
Both giving the same result: media/93939393hhs8.jpeg
string result=url.substring(url.substring(0,url.lastIndexOf('/')).lastIndexOf('/'));
or
Use Split and add last 2 items
string[] arr=url.split("/");
string result= arr[arr.length-2]+"/"+arr[arr.length-1]
public static String parseUrl(String str) {
return (str.lastIndexOf("/") > 0) ? str.substring(1+(str.substring(0,str.lastIndexOf("/")).lastIndexOf("/"))) : str;
}

Creating regex to extract 4 digit number from string using java

Hi I am trying to build one regex to extract 4 digit number from given string using java. I tried it in following ways:
String mydata = "get the 0025 data from string";
Pattern pattern = Pattern.compile("^[0-9]+$");
//Pattern pattern = Pattern.compile("^[0-90-90-90-9]+$");
//Pattern pattern = Pattern.compile("^[\\d]+$");
//Pattern pattern = Pattern.compile("^[\\d\\d\\d\\d]+$");
Matcher matcher = pattern.matcher(mydata);
String val = "";
if (matcher.find()) {
System.out.println(matcher.group(1));
val = matcher.group(1);
}
But it's not working properly. How to do this. Need some help. Thank you.
Change you pattern to:
Pattern pattern = Pattern.compile("(\\d{4})");
\d is for a digit and the number in {} is the number of digits you want to have.
If you want to end up with 0025,
String mydata = "get the 0025 data from string";
mydata = mydata.replaceAll("\\D", ""); // Replace all non-digits
Pattern pattern = Pattern.compile("\\b[0-9]+\\b");
This should do it for you.^$ will compare with the whole string.It will match string with only numbers.
Remove the anchors.. put paranthesis if you want them in group 1:
Pattern pattern = Pattern.compile("([0-9]+)"); //"[0-9]{4}" for 4 digit number
And extract out matcher.group(1)
Many better answers, but if you still have to use in the same way.
String mydata = "get the 0025 data from string";
Pattern pattern = Pattern.compile("(?<![-.])\\b[0-9]+\\b(?!\\.[0-9])");
Matcher matcher = pattern.matcher(mydata);
String val = "";
if (matcher.find()) {
System.out.println(matcher.group(0));
val = matcher.group(0);
}
changed matcher.group(1); to matcher.group(0);
You can go with \d{4} or [0-9]{4} but note that by specifying the ^ at the beginning of regex and $ at the end you're limiting yourself to strings that contain only 4 digits.
My recomendation: Learn some regex basics.
Scanner sc=new Scanner(System.in);
HashMap<String,String> a=new HashMap<>();
ArrayList<String> b=new ArrayList<>();
String s=sc.nextLine();
Pattern p=Pattern.compile("\\d{4}");
Matcher m=p.matcher(s);
while(m.find())
{
String x="";
x=x+(m.group(0));
a.put(x,"0");
b.add(x);
}
System.out.println(a.size());
System.out.println(b);
You can find all matched digit patterns and unique patterns (for unique use Set<String> k=b.keySet();)
If you want to match any number of digits then use pattern like the following:
^\D*(\d+)\D*$
And for exactly 4 digits go for
^\D*(\d{4})\D*$

Java: Replace all matching substrings of a string with their hashes

I would like to replace all matching substrings of a string with a hashing of them.
Lets say I have a string like this
String myString = "This is a A1B4F string with some 342BF matches FFABC that should be replaced.";
And now I would like to replace all the matching strings to regex (for example here "([a-fA-F\d]{5})" ) with their hashed value.
Assume that there is a sting method that gets as a parameter the substring and returns its sha1 value
public static String giveMeTheSha1Of(String myClearText){
return ....; (the sha1 value of the string)
}
How can I find all the matching substrings, and replace them with their hash?
Thank you Rohit Jain and Marko Topolnik. With your comments I found what I was searching for.
public static String replace5CharHex(String input){
String REGEX = "([a-fA-F\\d]{5})";
String tmpSubstring = "";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
tmpSubstring = hashManager.createNewHash(m.group());
m.appendReplacement(sb, tmpSubstring);
}
m.appendTail(sb);
return sb.toString();
}

How split a string using regex pattern

How split a [0] like words from string using regex pattern.0 can replace any integer number.
I used regex pattern,
private static final String REGEX = "[\\d]";
But it returns string with [.
Spliting Code
Pattern p=Pattern.compile(REGEX);
String items[] = p.split(lure_value_save[0]);
You have to escape the brackets:
String REGEX = "\\[\\d+\\]";
Java doesn't offer an elegant solution to extract the numbers. This is the way to go:
Pattern p = Pattern.compile(REGEX);
String test = "[0],[1],[2]";
Matcher m = p.matcher(test);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group());
}

Categories

Resources