In Java how to extract string from the phrase with split() function - java

Can I extract string from the phrase using split() function with subphrases as delimeters? For example I have a phrase "Mandatory string - Any string1 - Any string2". How can I extract "Any string1" with delimiters as "Mandatory string" and "[a-zA-Z]"
This is how I'm trying to extract:
String str="Mandatory string - Any string1 - Any string2";
String[] result= str.split("Mandatory\\string\\s-\\s|\\s-\\s[a-zA-Z]+");
Result of this code is
result = ["Mandatory string","ny string1","ny string2"]
But desired is:
result = ["Any string1"]
Could appreciate some help, thanks.

String[] result= str.split("Mandatory\\s(1)string\\s-\\s|\\s-\\s[a-zA-Z\\s(2)]+");
You just forgot an "s" in position(1)
and there should be a "\\s" in position(2)
try this line:
String[] result= str.split("Mandatory\\sstring\\s-\\s|\\s-\\s[a-zA-Z\\s]+");

First of all, there's a typo right here:
Mandatory\\string
This should probably read
Mandatory\\sstring
Anyway, I would either use " - " as the delimiter and get the second token:
str.split(" - ")[1] // TODO: prod version should do bounds checking etc
or use a different tool entirely, probably a regex match with the following regular expression:
"Mandatory string - (.*) - .*"
The parenthesised capture group will give you the string you're after.

Why not
String[] result = str.split(" - ");
return result.length < 2 ? "" : result[1];

If there is a definite format to your input string, just split it and then use the parts that are needed:
String[] resultArray = str.split(" - ");
String whatYouWant = resultArray[1];

Related

Regex split not working

I want split my string using regex.
String Str = " Dřevo5068Hlína5064Železo5064Obilí4895";
String reg = "(\\D+)(\\d+)(\\D+)(\\d+)(\\D+)(\\d+)(\\D+)(\\d+)";
if (Str.matches(reg)) {
String[] l = Str.split(reg);
System.out.println(Arrays.toString(l));
}
But, output is []. Where is problem?
Edit: I want split to:
Dřevo
5068
Hlína
5064
Železo
5064
Obilí
4895
Then I want get numbers from this String.
if your engine permits look-around, split using this pattern
(?<=\D)(?=\d)|(?<=\d)(?=\D)
Demo

Parsing String and Int in java

Im using java and I have a String that I would like to parse which contains the following
Logging v0.12.4
and would like to split it into a String containing
Logging
and an integer array containing
0.12.4
where
array[i][0] = 0
and
array[i][1] = 12
and so on. I have been stuck on this for a while now.
split your string on space to get Logging and v0.12.4
remove (substring) v from v0.12.4
split 0.12.4 on dot (use split("\\.") since dot is special in regex)
you can also parse each "0" "12" "4" to integer (Integer.parseInt can be helpful).
You can use a regex or just normal String splitting
String myString = "Logging v0.12.4";
String[] parts = myString.split(" v");
// now parts[0] will be "Logging" and
// parts[1] will be "0.12.4";
Then do the same for the version part:
String[] versionParts = parts[1].split("\\.");
// versionParts[0] will be "0"
// versionParts[1] will be "12"
// versionParts[2] will be "4"
You can "convert" these to integers by using Integer.parseInt(...)
Here ya go buddy, because I'm feeling generous today:
String string = "Logging v0.12.4";
Matcher matcher = Pattern.compile("(.+?)\\s+v(.*)").matcher(string);
if (matcher.matches()) {
String name = matcher.group(1);
int[] versions = Arrays.stream(matcher.group(2).split("\\.")).mapToInt(Integer::parseInt).toArray();
}

How to find the delimiter encountered in a string in JAVA

I have written simple program in Java which does manipulation of a given string.
The input string has some delimiters which are non-alphabets. I have used String Tokenizer to read and manipulate the individual words in a string.
Now I need to reconstruct this manipulated string with the same set of delimiters. Appreciate if any one can suggest me how to identify the delimiter.
In other words, this is what input is:
Text1 Delimiter1 Text2 Delimiter2 Text3 Delimiter3 Text4 Delimiter4
This is what my code does:
NewText1 NewText2 NewText3 NewText4
I made use of string tokenizer to identify the next token in this manner:
StringTokenizer st = new StringTokenizer(str, ", 0123456789(*&^%$##!-_)");
But now I would like to identify the delimiter that was encountered so that I can build my new string.
This is what I actually want:
NewText1 Delimiter1 NewText2 Delimiter2 NewText3 Delimiter3 NewText4 Delmiter4
You can proceed according to this:
String dels = "-, 0123456789(*&^%$##!_)";
String specs = "[" + dels + "]+";
String letts = "[^" + dels + "]+";
String text = "one, two - three! four";
String[] words = text.split( specs );
String[] delim = text.split( letts );
Note that in dels the hyphen must be up front. If you ever add [ or ] or ^ more care must be taken - check the javadoc in java.util.regex.Pattern.
There is no particular problem with composing the original string.
The disadvantage with StringTokenizer with a third argument is that it returns each delimiter as a separate token of length 1.

How to remove spaces in between the String

I have below String
string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
string = str.replace("\\s","").trim();
which returning
str = "Book Your Domain And Get Online Today."
But what is want is
str = "Book Your Domain And Get Online Today."
I have tried Many Regular Expression and also googled but got no luck. and did't find related question, Please Help, Many Thanks in Advance
Use \\s+ instead of \\s as there are two or more consecutive whitespaces in your input.
string = str.replaceAll("\\s+"," ")
You can use replaceAll which takes a regex as parameter. And it seems like you want to replace multiple spaces with a single space. You can do it like this:
string = str.replaceAll("\\s{2,}"," ");
It will replace 2 or more consecutive whitespaces with a single whitespace.
First get rid of multiple spaces:
String after = before.trim().replaceAll(" +", " ");
If you want to just remove the white space between 2 words or characters and not at the end of string
then here is the
regex that i have used,
String s = " N OR 15 2 ";
Pattern pattern = Pattern.compile("[a-zA-Z0-9]\\s+[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(s);
while(m.find()){
String replacestr = "";
int i = m.start();
while(i<m.end()){
replacestr = replacestr + s.charAt(i);
i++;
}
m = pattern.matcher(s);
}
System.out.println(s);
it will only remove the space between characters or words not spaces at the ends
and the output is
NOR152
Eg. to remove space between words in a string:
String example = "Interactive Resource";
System.out.println("Without space string: "+ example.replaceAll("\\s",""));
Output:
Without space string: InteractiveResource
If you want to print a String without space, just add the argument sep='' to the print function, since this argument's default value is " ".
//user this for removing all the whitespaces from a given string for example a =" 1 2 3 4"
//output: 1234
a.replaceAll("\\s", "")
String s2=" 1 2 3 4 5 ";
String after=s2.replace(" ", "");
this work for me
String string_a = "AAAA BBB";
String actualTooltip_3 = string_a.replaceAll("\\s{2,}"," ");
System.out.println(String actualTooltip_3);
OUTPUT will be:AAA BBB

Splitting strings with multiple lines in android

I have the following string:
"ISL-1027
20:13:02:22:00:76"
i.e. bluetooth name and MAC address
I need MAC address on a separate string.
What is the best way to use split() in this case?
Thanks
split("\n") you can use this."\n" will be the separator here.
String str = "ISL-1027" +
"\n" +
"20:13:02:22:00:76";
String[] arr= str.split("\n");
System.out.println("Bluetooth Name: "+arr[0]);
System.out.println("MAC address: "+arr[1]);
Out put:
Bluetooth Name: ISL-1027
MAC address: 20:13:02:22:00:76
If your input String like this ISL-1027 20:13:02:22:00:76(separate by a space) use follows
String str = "ISL-1027 20:13:02:22:00:76";
String[] arr= str.split(" ");
System.out.println("Bluetooth Name: "+arr[0]);
System.out.println("MAC address: "+arr[1]);
Split matching on any white space and include the DOTALL mode switch:
split("(?s)\\s+");
The DOTALL will make the regex work despite the presence of newlines.
Depending on that how your string is formated is not sure, but the format of a mac-address is defined. I would not try to split the string and hope that index n is the correct value.
Instead I would use regulare expression to find the correct position of a string that matches the mac-address format.
Here is a litle example (not tested):
String input = "ISL-1027
20:13:02:22:00:76"
Pattern macAddrPattern = Pattern.compile("[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\");
String macAdr = parseMacAddr(input);
public String parseMacAddr(String value) {
Matcher m = macAddrPattern.matcher(value);
if (m.matches()) {
return value.substring(m.start(),m.end());
}
return null;
}
This should always work.

Categories

Resources