How to extract specific letters in string with java - java

I have some expression in a Java string and a would get the letter, which was on the left side and on the right side of a specific sign.
Here are two examples:
X-Y
X-V-Y
Now, I need to extract in the first example the letter X and Y in a separate string. And in the second example, I need to extract the letters X, V and Y in a separate string.
How can i implemented this requirement in Java?

Try with:
String input = "X-V-Y";
String[] output = input.split("-"); // array with: "X", "V", "Y"

use String.split method with "-" token
String input = "X-Y-V"
String[] output = input.split("-");
now in the output array there will be 3 elements X,Y,V

String[] results = string.split("-");

do like this
String input ="X-V-Y";
String[] arr=input.split("-");
output
arr[0]-->X
arr[1]-->V
arr[2]-->Y

I'm getting in on this too!
String[] terms = str.split("\\W"); // split on non-word chars

You can use this method :
public String[] splitWordWithHyphen(String input) {
return input.split("-");
}

you can extract and handle a string by using the following code:
String input = "x-v-y";
String[] extractedInput = intput.split("-");
for (int i = 0; i < extractedInput.length - 1; i++) {
System.out.print(exctractedInput[i]);
}
Output: xvy

Related

Java - Split and trim in one shot

I have a String like this : String attributes = " foo boo, faa baa, fii bii," I want to get a result like this :
String[] result = {"foo boo", "faa baa", "fii bii"};
So my issue is how should to make split and trim in one shot i already split:
String[] result = attributes.split(",");
But the spaces still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
I know that we can make a loop and make trim for every one but I want to makes it in shot.
Use regular expression \s*,\s* for splitting.
String result[] = attributes.split("\\s*,\\s*");
For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:
String result[] = attributes.trim().split("\\s*,\\s*");
Using java 8 you can do it like this in one line
String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
If there is no text between the commas, the following expression will not create empty elements:
String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");
You can do it with Google Guava library this way :
List<String> results = Splitter.on(",").trimResults().splitToList(attributes);
which I find quite elegant as the code is very explicit in what it does when you read it.
ApaceCommons StringUtils.stripAll function can be used to trim individual elements of an array. It leaves the null as null if some of your array elements are null.
Here,
String[] array = StringUtils.stripAll(attributes.split(","));
create your own custom function
private static String[] split_and_trim_in_one_shot(String string){
String[] result = string.split(",");
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
Overload with a consideration for custom delimiter
private static String[] split_and_trim_in_one_shot(String string, String delimiter){
String[] result = string.split(delimiter);
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
with streams
public static List<String> split(String str){
return Stream.of(str.split(","))
.map(String::trim)
.map (elem -> new String(elem))//optional
.collect(Collectors.toList());
What about spliting with comma and space:
String result[] = attributes.split(",\\s");
// given input
String attributes = " foo boo, faa baa, fii bii,";
// desired output
String[] result = {"foo boo", "faa baa", "fii bii"};
This should work:
String[] s = attributes.trim().split("[,]");
As answered by #Raman Sahasi:
before you split your string, you can trim the trailing and leading spaces. I've used the delimiter , as it was your only delimiter in your string
String result[] = attributes.trim().split("\\s*,[,\\s]*");
previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/
Best way is:
value.split(",").map(function(x) {return x.trim()});

Regex for int Array

I need to validate a string argument if it can be converted to an int Array.
String pattern = "(\\d+[,])+";
String test = "18,32,5,8,10";
test2.matches(pattern2) //returns false as i requires , in the end
Is there any way to ignore last ' , '
Use a group construct to specify that digits should be followed by (, digits) ...
\\d+(?:,\\d+)+
Regex for both array and single element
(\d|\[(\d|,\s*)*])
This regex will work for you (checks for a "valid array") :
public static void main(String[] args) {
String s = "18,32,5,8,10";
System.out.println(s.matches("(?!.*,$)(?!,.*$)(\\d+(?:,|$))+"));
}
Checks and fails for:
multiple continuous commas
comma at beginning
comma at end
You can try
Pattern = "^\d+(,\d+)*$"
text = "10,5,10" (TRUE)
text = "10,5,10," (FALSE)
text = "10,5,10 " (FALSE)
Since I don't know how to use regex and if I were in your place then this would have been my way to do so
String test = "18,32,5,8,10";
String str[]=test.split(",");
int ar[] = new int[str.length];
for(int i = 0; i<ar.length; i++){
ar[i] = Integer.parseInt(str[i]);
}
The problem in this code if any I can see is this that call to parseInt() method must be wrapped in try-catch as it can throw NumberFormatException if your string contains value other than digit and comma(,).

About Java input string filter

I have a very simple question about JAVA string filter
I to want input this command to console.
add 100#10
which means execute add method input arguments 100 and 10 respectively.
I used
String[] s = str.split("#");
String a = s[0];// here can get 100
String b=s1];// get can get 10
I have two questions
first is how to do delete the at (#) character before put it to string.split()
second can anyone can provide some better solution to handle this kind of input ?
such as
add 1000#10 //only add,1000,10 need to take
times 1000#10 //only add,1000,10 need to take
You can split on multiple tokens because it's a regex parameter:
String a[] = "aadd 100#200".split("[ #]");
returns ["aadd", "100", "200"]
Then you can do
String command = a[0];
String operand1 = a[1];
String operand2 = a[2];
not as sexy as ergonaut's solution, but you also can use two splits:
String[] arr1 = "add 100#10".split(" ");
String[] arr2 = arr1[1].split("#");
String[] result = [arr1[0], arr2[0], arr2[1]];
should be
["add","100","10"]; // this is result
greetings

How to extract integers from a complicated string?

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

Making multiple searches in a string using scanner or string methods (java)

I need to extract several integers from a string that looks like this:
22:43:12:45
I need to extract 22, 43, 12, and 45 as separate integers. I need to use string methods or scanner methods to read up until : and extract the 22. Then read between the first : and second : to give me 43, and so on.
I can extract up to the first : no problem, but I down know what to do thereafter.
Any help would be much appreciated.
String[] parts = str.split(":");
int[] numbers = new int[parts.length];
Iterate over this String array to get an array of integers:
int index = 0;
for(String part : parts)
numbers[index++] = Integer.parseInt(part);
You should look at String.split method . Given a regular expression, this methods splits the string based on that. In your case the regular expression is a ":"
String s ="22:43:12:45";
int i =0;
for (String s1 : s.split(":")) { // For each string in the resulting split array
i = Integer.parseInt(s1);
System.out.println(i);
}
The split returns a string array with your string separated. So in this case , The resulting string array will have "22" on the 0th position, "43" on the first position and so on. To convert these to integers you can use the parseInt method which takes in a string and gives the int equivalent.
You can use only indexOf and substring methods of String:
String text = "22:43:12:45";
int start = 0;
int colon;
while (start < text.length()) {
colon = text.indexOf(':', start);
if (colon < 0) {
colon = text.length();
}
// You can store the returned value somewhere, in a list for example
Integer.parseInt(text.substring(start, colon)));
start = colon + 1;
};
Using Scanner is even simpler:
String text = "22:43:12:45";
Scanner scanner = new Scanner(text);
scanner.useDelimiter(":");
while (scanner.hasNext()) {
// Store the returned value somewhere to use it
scanner.nextInt();
}
However, String.split is the shortest solution.
Make a regex like
(\d\d):(\d\d):(\d\d):(\d\d)

Categories

Resources