I am having a hard time figuring with out. Say I have String like this
String s could equal
s = "{1,4,204,3}"
at another time it could equal
s = "&5,3,5,20&"
or it could equal at another time
s = "/4,2,41,23/"
Is there any way I could just extract the numbers out of this string and make a char array for example?
You can use regex for this sample:
String s = "&5,3,5,20&";
System.out.println(s.replaceAll("[^0-9,]", ""));
result:
5,3,5,20
It will replace all the non word except numbers and commas. If you want to extract all the number you can just call split method -> String [] sArray = s.split(","); and iterate to all the array to extract all the number between commas.
You can use RegEx and extract all the digits from the string.
stringWithOnlyNumbers = str.replaceAll("[^\\d,]+","");
After this you can use split() using deliminator ',' to get the numbers in an array.
I think split() with replace() must help you with that
Use regular expressions
String a = "asdf4sdf5323ki";
String regex = "([0-9]*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(a);
while (matcher.find())
{
String group = matcher.group(1);
if (group.length() > 0)
{
System.out.println(group);
}
}
from your cases, if the pattern of string is same in all cases, then something like below would work, check for any exceptions, not mentioned here :
String[] sArr= s.split(",");
sArr[0] = sArr[0].substring(1);
sArr[sArr.length()-1] =sArr[sArr.length()-1].substring(0,sArr[sArr.length()-1].length()-1);
then convert the String[] to char[] , here is an example converter method
You can use Scanner class with , delimiter
String s = "{1,4,204,3}";
Scanner in = new Scanner(s.substring(1, s.length() - 1)); // Will scan the 1,4,204,3 part
in.useDelimiter(",");
while(in.hasNextInt()){
int x = in.nextInt();
System.out.print(x + " ");
// do something with x
}
The above will print:
1 4 204 3
Related
I have a file name with this format yy_MM_someRandomString_originalFileName.
example:
02_01_fEa3129E_my Pic.png
I want replace the first 2 underscores with / so that the example becomes:
02/01/fEa3129E_my Pic.png
That can be done with replaceAll, but the problem is that files may contain underscores as well.
#Test
void test() {
final var input = "02_01_fEa3129E_my Pic.png";
final var formatted = replaceNMatches(input, "_", "/", 2);
assertEquals("02/01/fEa3129E_my Pic.png", formatted);
}
private String replaceNMatches(String input, String regex,
String replacement, int numberOfTimes) {
for (int i = 0; i < numberOfTimes; i++) {
input = input.replaceFirst(regex, replacement);
}
return input;
}
I solved this using a loop, but is there a pure regex way to do this?
EDIT: this way should be able to let me change a parameter and increase the amount of underscores from 2 to n.
You could use 2 capturing groups and use those in the replacement where the match of the _ will be replaced by /
^([^_]+)_([^_]+)_
Replace with:
$1/$2/
Regex demo | Java demo
For example:
String regex = "^([^_]+)_([^_]+)_";
String string = "02_01_fEa3129E_my Pic.png";
String subst = "$1/$2/";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
String result = matcher.replaceFirst(subst);
System.out.println(result);
Result
02/01/fEa3129E_my Pic.png
Your current solution has few problems:
It is inefficient - because each replaceFirst need to start from beginning of string so it needs to iterate over same starting characters many times.
It has a bug - because of point 1. while iterating from beginning instead of last modified place, we can replace value which was inserted previously.
For instance if we want to replace single character two times, each with X like abc -> XXc after code like
String input = "abc";
input = input.replaceFirst(".", "X"); // replaces a with X -> Xbc
input = input.replaceFirst(".", "X"); // replaces X with X -> Xbc
we will end up with Xbc instead of XXc because second replaceFirst will replace X with X instead of b with X.
To avoid that kind of problems you can rewrite your code to use Matcher#appendReplacement and Matcher#appendTail methods which ensures that we will iterate over input once and can replace each matched part with value we want
private static String replaceNMatches(String input, String regex,
String replacement, int numberOfTimes) {
Matcher m = Pattern.compile(regex).matcher(input);
StringBuilder sb = new StringBuilder();
int i = 0;
while(i++ < numberOfTimes && m.find() ){
m.appendReplacement(sb, replacement); // replaces currently matched part with replacement,
// and writes replaced version to StringBuilder
// along with text before the match
}
m.appendTail(sb); //lets add to builder text after last match
return sb.toString();
}
Usage example:
System.out.println(replaceNMatches("abcdefgh", "[efgh]", "X", 2)); //abcdXXgh
I'm trying to convert a string array that is itself a part of another array fed into Java from an external file.
There are two parts to this question:
How do I convert the string's substring elements to doubles or ints?
How do I skip the header which is itself a part of the string?
I have the following piece of code that is NOT giving me an error but neither is it giving me output. The data is arranged in columns, so as far as the split, I'm not sure what delimiter to use as the argument for that method. I've tried \r, \n, ",", " " and nothing works.
str0 = year.split(",");
year = year.trim();
int[] yearData = new int[str0.length-1];
for(i = 0; i < str0.length-1; i++) {
yearData[i] = Integer.parseInt(str0[i]);
System.out.println(yearData[i]);
}
The code you have provided is not working. Anyway consider the given example which is using Regular Expression, where you found all the numbers in the string, so our regular expression works well. By changing the Regular Expression you can get the substring as well as you can skip the head part. I hope it would help.
String regEx = "[+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)";
String str = "256 is the square of 16 and -2.5 squared is 6.25 “ + “and -.243 is less than 0.1234.";
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);
int i = 0;
String subStr = null;
while(m.find()) {
System.out.println(m.group());
Try something like this:
year = year.trim(); // This should come before the split()...
str0 = year.split("[\\s,;]+"); // split() uses RegEx...
int[] yearData = new int[str0.length-1];
for(i = 0; i < str0.length-1; i++) {
yearData[i] = Integer.parseInt(str0[i]);
System.out.println(yearData[i]);
}
I have trouble splitting string based on regex.
String str = "1=(1-2,3-4),2=2,3=3,4=4";
Pattern commaPattern = Pattern.compile("\\([0-9-]+,[0-9-]+\\)|(,)") ;
String[] arr = commaPattern.split(str);
for (String s : arr)
{
System.out.println(s);
}
Expected output,
1=(1-2,3-4)
2=2
3=3
4=4
Actual output,
1=
2=2
3=3
4=4
This regex would split as required
,(?![^()]*\\))
------------
|->split with , only if it is not within ()
This isn't well suited for a split(...). Consider scanning through the input and matching instead:
String str = "1=(1-2,3-4),2=2,3=3,4=4";
Matcher m = Pattern.compile("(\\d+)=(\\d+|\\([^)]*\\))").matcher(str);
while(m.find()) {
String key = m.group(1);
String value = m.group(2);
System.out.printf("key=%s, value=%s\n", key, value);
}
which would print:
key=1, value=(1-2,3-4)
key=2, value=2
key=3, value=3
key=4, value=4
You will have to use some look ahead mechanism here. As I see it you are trying to split it on comma that is not in parenthesis. But your regular expressions says:
Split on comma OR on comma between numbers in parenthesis
So your String gets splitted in 4 places
1) (1-2,3-4)
2-4) comma
String[] arr = commaPattern.split(str);
should be
String[] arr = str.split(commaPattern);
I'm trying to split the string with double pipe(||) being the delimiter.String looks something like this:
String str ="user#email1.com||user#email2.com||user#email3.com";
i'm able to split it using the StringTokeniser.The javadoc says the use of this class is discouraged and instead look at String.split as option.
StringTokenizer token = new StringTokenizer(str, "||");
The above code works fine.But not able to figure out why below string.split function not giving me expected result..
String[] strArry = str.split("\\||");
Where am i going wrong..?
String.split() uses regular expressions. You need to escape the string that you want to use as divider.
Pattern has a method to do this for you, namely Pattern.quote(String s).
String[] split = str.split(Pattern.quote("||"));
You must escape every single | like this str.split("\\|\\|")
try this bellow :
String[] strArry = str.split("\\|\\|");
You can try this too...
String[] splits = str.split("[\\|]+");
Please note that you have to escape the pipe since it has a special meaning in regular expression and the String.split() method expects a regular expression argument.
For this you can follow two different approaches you can follow whichever suites you best:
Approach 1:
By Using String SPLIT functionality
String str = "a||b||c||d";
String[] parts = str.split("\\|\\|");
This will return you an array of different values after the split:
parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"
Approach 2:
By using PATTERN and MATCHER
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String str = "a||b||c||d";
Pattern p = Pattern.compile("\\|\\|");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println("Found two consecutive pipes at index " + m.start());
}
This will give you the index positions of consecutive pipes:
parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"
Try this
String yourstring="Hello || World";
String[] storiesdetails = yourstring.split("\\|\\|");
I am rather new at java, and I know this cant be too difficult, but I cant quite figure it out.
String xxChange = request.getParameter("XXChange");
String yyChange = request.getParameter("YYChange");
String zzChange = request.getParameter("ZZChange");
String aaaChange = request.getParameter("AAChange");
So basically I am getting these parameters and just setting them to strings. Each one of these strings has multiple numbers then two letters after it, and my question is how do I remove the letters and set it to a new string. Fyi....the number in front of the letters is on a sequence, and could grow from being 1 digit to multiple, so i dont think i can do string.Substring.
You want to remove the last two characters, so use substring like this:
String s = "123AB";
String numbers = s.substring(0, s.length() - 2);
You could test something like
String value = "123ABC";
System.out.println(value.replaceAll("\\d+(.*)", "$1"));
If you only need the last two letters:
String input = "321Ab";
String lastTwo = input.substring(input.length() - 2);
If you need both the digits and the letters use a regular expression:
Pattern p = Pattern.compile("(\\d+)(\\w{2})");
Matcher m = p.matcher("321Ab");
if (m.matches()) {
int number = Integer.parseInt(m.group(1)); // 321
String letters = m.group(2); // Ab
...
}