Is there any pretty and flexible way to format String data into specific pattern, for example:
data input -> 0123456789
data output <- 012345/678/9
I did it by cutting String into multiple parts, but I'm searching for any more suitable way.
Assuming you want the last and 4th-2nd last in groups:
String formatted = str.replaceAll("(...)(.)$", "/$1/$2");
This captures the parts you want in groups and replaces them with intervening slashes.
You can use replaceAll with regex to match multiple groups like so :
String text = "0123456789";
text = text.replaceAll("(\\d{6})(\\d{3})(.*)", "$1/$2/$3");
System.out.println(text);
Output
012345/678/9
details
(\d{6}) group one match 6 digits
(\d{3}) group two match 3 digits
(.*) group three rest of your string
$1/$2/$3 replace with the group 1 followed by / followed by group 2 followed by / followed by group 3
You can use StringBuilder's insert to insert characters at a certain index:
String input = "0123456789";
String output = new StringBuilder(input)
.insert(6, "/")
.insert(10, "/")
.toString();
System.out.println(output); // 012345/678/9
Related
I want to replace all the text within brackets to uppercase letters for any String object. For example if the text is - Hi (abc), how (a)re (You)?" , output should be - Hi ABC, how Are YOU? . I tried to use StringUtils.SubstringBetween(), but that replaces only the first substring between ().
Using regex, I suppose the group() method requires the count of such substrings. What is the correct direction to be taken?
Since Java 9 we can use Matcher.replaceAll​(Function<MatchResult,String> replacer)
String str = "Hi (abc), how (a)re (You)?";
Pattern p = Pattern.compile("\\((.*?)\\)"); //matches parenthesis and places
//content between them in group 1
String replaced = p.matcher(str)
.replaceAll(match -> match.group(1).toUpperCase()); //replace each match with
//content of its group 1 in its upper case
System.out.println(replaced);
Output: Hi ABC, how Are YOU?
I am trying to find and replace a part of the string which contains an integer.
String str = "I <FS:20>am in trouble.</FS>";
I need to replace and
for /FS I am using
str = str.replace("</FS>", "\\fs0");
I am not sure how to approach the FS:20 because the 20 is a variable and in some cases might be a different number which means that I need to somehow the int part.
Input :
"I FS:20 am in trouble.";
Output :
"I \fs20 am in trouble.";
but 20 is not a fixed variable so I can't hardcode it
One way to do it is to make two replacements:
str = str.replaceAll("</FS>", "");
str = str.replaceAll("<FS:(\\d+)>", "\\\\fs$1");
System.out.println(str);
Output:
I \fs20am in trouble.
The first replacement just removes </FS> from the string.
The second replacement makes use of a RegEx pattern <FS:(\d+)>.
The RegEx pattern matches the literal characters <FS: followed by one or more digits, which it stores in group 1 (\d+), finally followed by the character >
The value stored in group 1 can be used in the replacement string using $1, so \\\\fs$1 will be a backslash \ followed by fs followed by the contents of group 1 (\d+), in this case 20.
The numbers matched by \d+ are stored in group 1, accessed using $1
If you can use your variable that is 20 in described case.
Integer yourVariable=20;
String str = "I <FS:20>am in trouble.</FS>";
str = str.replace("<FS:"+yourVariable+">", "\\fs0");
Does anyone have an idea how I can split a string returned by a WS to different strings?
String wsResult = "SONACOM RC, RUE DES ETOILES N. 20, 75250 PARIS (MI)";
I'm trying to split it into:
String name = "SONACOM RC";
String adress = "RUE DES ETOILES N. 20";
String postalCode = "75250";
String city = "PARIS";
N.B: the return of the WS changes only what is inside of my parameters
Thank you in advance for your help
You could capture your data in 4 capturing groups. Your provided example uses uppercase characters, which you can match with [A-Z].
If you want to match also lowercase characters, digits and an underscore, you could replace [A-Z] or [A-Z\d] with \w.
You can go about this in multiple ways. An approach could be:
([A-Z ]+), +([A-Z\d .]+), +(\d+) +([A-Z\d() ]+)
Explanation
Group 1: match one or more uppercase characters or a whitespace ([A-Z ]+)
Match a comma and one or more whitespaces , +
Group 2: match one or more uppercase characters or digit or whitespace or dot ([A-Z\d .]+)
Match a comma and one or more whitespaces , +
Group 3: match one or more digits (\d+)
Match one or more whitespaces +
Group 4: match one or more uppercase characters or digit or open/close parenthesis or whitespace ([A-Z\d() ]+)
Output in Java
One easy way to split it as you'd like is using wsResult.split(","). However, you'll have to add a comma between 75250 and Paris:
String wsResult = "SONACOM RC, RUE DES ETOILES N. 20, 75250, PARIS (MI)";
String[] temp = wsResult.split(",");
String name = temp[0];
String adress = temp[1];
String postalCode = temp[2];
String city = temp[3];
Using that you will get the output you're looking for.
EDIT
Another way to get your output without adding a comma would be to do this (using the code above too):
for(int i = 1; i<postalCode.length(); i++){
if(postalCode.charAt(i) == ' ') {
city = postalCode.substring(i,postalCode.length());
postalCode = postalCode.substring(0,i);
break;
}
}
For more information check the String class in the API Java and this Stack Overflow question.
I have string something like :
SKU: XP321654
Quantity: 1
Order date: 01/08/2016
The SKU length is not fixed , so my function sometime returns me the first or two characters of Quantity also which I do not want to get. I want to get only SKU value.
My Code :
int index = Content.indexOf("SKU:");
String SKU = Content.substring(index, index+15);
If SKU has one or two more digits then also it is not able to get because I have specified limit till 15. If I do index + 16 to get long SKU data then for Short SKU it returns me some character of Quantity also.
How can I solve it. Is there any way to use instead of a static string character length as limit.
My SKU last digit will always number so any other thing which I can use to get only SKU till it's last digit?
Using .substring is simply not the way to process such things. What you need is a regex (or regular expression):
Pattern pat = Pattern.compile("SKU\\s*:\\s*(\\S+)");
String sku = null;
Matcher matcher = pattern.matcher(Content);
if(matcher.find()) { //we've found a match
sku = matcher.group(1);
}
//do something with sku
Unescaped the regex is something like:
SKU\s*:\s*(\S+)
you are thus looking for a pattern that starts with SKU then followed by zero or more \s (spacing characters like space and tab), followed by a colon (:) then potentially zero or more spacing characters (\s) and finally the part in which you are interested: one or more (that's the meaning of +) non-spacing characters (\S). By putting these in brackets, these are a matching group. If the regex succeeds in finding the pattern (matcher.find()), you can extract the content of the matching group matcher.group(1) and store it into a string.
Potentially you can improve the regex further if you for instance know more about how a SKU looks like. For instance if it consists only out of uppercase letters and digits, you can replace \S by [0-9A-Z], so then the pattern becomes:
Pattern pat = Pattern.compile("SKU\\s*:\\s*([0-9A-Z]+)");
EDIT: for the quantity data, you could use:
Pattern pat2 = Pattern.compile("Quantity\\s*:\\s*(\\d+)");
int qt = -1;
Matcher matcher = pat2.matcher(Content);
if(matcher.find()) { //we've found a match
qt = Integer.parseInt(matcher.group(1));
}
or see this jdoodle.
You know you can just refer to the length of the string right ?
String s = "SKU: XP321654";
String sku = s.substring(4, s.length()).trim();
I think using a regex is clearly overkill in this case, it is way way simpler than this. You can even split the expression although it's a bit less efficient than the solution above, but please don't use a regex for this !
String sku = "SKU: XP321654".split(':')[1].trim();
1: you have to split your input by lines (or split by \n)
2: when you have your line: you search for : and then you take the remaining of the line (with the String size as mentionned in Dici answer).
Depending on how exactly the string contains new lines, you could do this:
public static void main(String[] args) {
String s = "SKU: XP321654\r\n" +
"Quantity: 1\r\n" +
"Order date: 01/08/2016";
System.out.println(s.substring(s.indexOf(": ") + 2, s.indexOf("\r\n")));
}
Just note that this 1-liner has several restrictions:
The SKU property has to be first. If not, then modify the start index appropriately to search for "SKU: ".
The new lines might be separated otherwise, \R is a regex for all the valid new line escape characters combinations.
Hi please help me out in getting regular expression for the
following requirement
I have string type as
String vStr = "Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)";
String sStr = "Every 1 form(s) - Earth: (Air,Fire) ";
from these strings after using regex I need to get values as "Air,Earth,Water sea,Fire" and "Air,Fire"
that means after
String vStrRegex ="Air,Earth,Water sea,Fire";
String sStrRegex ="Air,Fire";
All the strings that are input will be seperated by ":" and values needed are inside brackets always
Thanks
The regular expression would be something like this:
: \((.*?)\)
Spelt out:
Pattern p = Pattern.compile(": \\((.*?)\\)");
Matcher m = p.matcher(vStr);
// ...
String result = m.group(1);
This will capture the content of the parentheses as the first capture group.
Try the following:
\((.*)\)\s*$
The ending $ is important, otherwise you'll accidentally match the "(s)".
If you have each string separately, try this expression: \(([^\(]*)\)\s*$
This would get you the content of the last pair of brackets, as group 1.
If the strings are concatenated by : try to split them first.
Ask yourself if you really need a regex. Does the text you need always appear within the last two parentheses? If so, you can keep it simple and use substring instead:
String vStr = "Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)";
int lastOpeningParens = vStr.lastIndexOf('(');
int lastClosingParens = vStr.lastIndexOf(')');
String text = vStr.substring(lastOpeningParens + 1, lastClosingParens);
This is much more readable than a regex.
I assume that there are only whitespace characters between : and the opening bracket (:
Pattern regex = Pattern.compile(":\\s+\\((.+)\\)");
You'll find your results in capturing group 1.
Try this regex:
.*\((.*)\)
$1 will contain the required string