Java: removing the first word in split - java

i want to split a String by whitespaces and remove the First match.
Since doing this seperatly would be in O(n) i wonder if there is a Regex for doing this?
e.g.:
String s = "asd wer gfb";
String sA[] = s.split(magixRegex);
than sA should contain:
["wer", "gfb"]

Replace the first word and then do splitting.
String s = "asd wer gfb";
String sA[] = s.replaceFirst("^\\S+\\s*", "").split("\\s+");
System.out.println(Arrays.toString(sA));

You could substring it first:
String s = "asd wer gfb";
s = s.substring( s.indexOf(' ') + 1 );
String sA[] = s.split(" ");

Related

Split the string with hyphen symbol multiple occurrence using regex /java

Getting the string value using the below xpath
String noAndDate = driver.findElement(By.xpath("//*[#id='c38']/div/table/tbody/tr[1]/td/strong")).getText();
Output of the above string = 2928554 - 2009-09-18 (BOPI 2009-38)
my expected output
2928554
2009-09-18
i tried below split, but i'm not getting my expected output
String[] words = noAndDate.split("-");
Please advice/help me
You can instead try splitting on a regex alternation which looks for a hyphen surrounded by whitespace, or pure whitespace:
String input = "2928554 - 2009-09-18 (BOPI 2009-38)";
String[] parts = input.split("(\\s+-\\s+|\\s+)");
System.out.println(parts[0]);
System.out.println(parts[1]);
Demo
Try the below code-
String str = "2928554 - 2009-09-18 (BOPI 2009-38)";
String str1 = str.split(" - | ")[0];
String str2 = str.split(" - | ")[1];
This will return str1 as 2928554 and str2 as 2009-09-18.
Hope this will help you !
Just split with regex will do.
String given = "2928554 - 2009-09-18 (BOPI 2009-38)";
String [] splitted = given.split(" - |\\s+");
String result = splitted[0] +", "+splitted[1];
System.out.println(result);
prints
2928554, 2009-09-18
Use Regex capture groups, here you can see what you want in 2 groups:
(\d+)\s*-\s*(\d+\-\d+\-\d+)
() = group
Try this:
String[] words = noAndDate.split(" ");
then
System.out.println(words[0]);
System.out.println(words[2]);

How to replace or convert the first occurrence of a dot from a string in java

Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");

Cut ':' && " " from a String with a tokenizer

right now I am a little bit confused. I want to manipulate this string with a tokenizer:
Bob:23456:12345 Carl:09876:54321
However, I use a Tokenizer, but when I try:
String signature1 = tok.nextToken(":");
tok.nextToken(" ")
I get:
12345 Carl
However I want to have the first int and the second int into a var.
Any ideas?
You have two different patterns, maybe you should handle both separated.
Fist you should split the space separated values. Only use the string split(" "). That will return a String[].
Then for each String use tokenizer.
I believe will works.
Code:
String input = "Bob:23456:12345 Carl:09876:54321";
String[] words = input.split(" ")
for (String word : words) {
String[] token = each.split(":");
String name = token[0];
int value0 = Integer.parseInt(token[1]);
int value1 = Integer.parseInt(token[2]);
}
Following code should do:
String input = "Bob:23456:12345 Carl:09876:54321";
StringTokenizer st = new StringTokenizer(input, ": ");
while(st.hasMoreTokens())
{
String name = st.nextToken();
String val1 = st.nextToken();
String val2 = st.nextToken();
}
Seeing as you have multiple patterns, you cannot handle them with only one tokenizer.
You need to first split it based on whitespace, then split based on the colon.
Something like this should help:
String[] s = "Bob:23456:12345 Carl:09876:54321".split(" ");
System.out.println(Arrays.toString(s ));
String[] so = s[0].split(":", 2);
System.out.println(Arrays.toString(so));
And you'd get this:
[Bob:23456:12345, Carl:09876:54321]
[Bob, 23456:12345]
If you must use tokeniser then I tink you need to use it twice
String str = "Bob:23456:12345 Carl:09876:54321";
StringTokenizer spaceTokenizer = new StringTokenizer(str, " ");
while (spaceTokenizer.hasMoreTokens()) {
StringTokenizer colonTokenizer = new StringTokenizer(spaceTokenizer.nextToken(), ":");
colonTokenizer.nextToken();//to igore Bob and Carl
while (colonTokenizer.hasMoreTokens()) {
System.out.println(colonTokenizer.nextToken());
}
}
outputs
23456
12345
09876
54321
Personally though I would not use tokenizer here and use Claudio's answer which splits the strings.

Parse string starting from the end

I want to split string around only the last _ character , example:some_string_foo_bar into two substrings some_string_foo bar.
I tried to use Pattern and StringTokenizer, but they always start from the beginning of stirng. Any idea how to do this?
Use lastIndexOf; there's no reason to do a full split.
Sure, this might be of some use. Here's an example.
String source = "hello_world_foo";
int pos = source.lastIndexOf('_');
String before = source.substring(0, pos);
String after = source.substring(pos + 1);
You can use:
String strX = "some_string_foo";
String str1 = strX.substring(0,strX.lastIndexOf("_"));
String str2 = strX.subscting(strX.lastIndexOf("_"),strX.length());
String[] arr = str.split("_");
String lastOne = arr[arr.length-1];

Making a song name out of a URL

I have a URL and I want it to look like this:
Action Manatee - Action
http://xxxxxx.com/songs2/Music%20Promotion/Stream/Action%20Manatee%20-%20Action.mp3
What is the syntax for trimming up to where it after this "Stream/" and make spaces where the %20 is. I also want to trim the .mp3
Hmm, for that particular example, I would split the string according to the '/' character then trim the text that follows the final '.' character. Finally, do a replace of "%20" into " ". That should leave you with the string you want
Tested
String initial = "http://xxxxxx.com/songs2/Music%20Promotion/Stream/Action%20Manatee%20-%20Action.mp3";
String[] split = initial.split("/");
String output = split[split.length-1];
int length = output.lastIndexOf('.');
output = output.substring(0, length);
output = output.replace("%20", " ");
String urlParts[] = URL.split("\/");
String urlLast = urlParts[length-1];
String nameDotMp = urlLast.replaceAll("%20");
String name = nameDotMp.substring(0,nameDotMp.length-5);
You could use the split() and replace() methods to accomplish this, here are two ways:
Split your string apart by using the forward slashes:
string yourUrl = [URL Listed];
//Breaks your URL into sections on slashes
string[] sections = yourUrl.split("\/");
//Grabs the last section after the slashes, and replaces the %20 with spaces
string newString = sections[sectiongs.length-1].replace("%20"," ");
Split your string at the Stream/ section: (Only use this if you can guarantee it will be in that form)
string yourUrl = [URL Listed];
//This will get everything after Stream (your song name)
string newString = yourUrl.split("Stream\/")[1];
//Replaces your %20s with spaces
newString = newString.replace("%20"," ");
URL songURL = new URL("yourpath/filename");
String filename = songURL.getFile();

Categories