Splitting of String delimited by '[' and ']' [duplicate] - java

This question already has answers here:
java regular expression to extract content within square brackets
(3 answers)
How do I split a string in Java?
(39 answers)
Closed 8 years ago.
I have some sampel data written on a file. The data are in the following format -
[Peter Jackson] [UK] [United Kingdom] [London]....
I have to extract the information delimited by '[' and ']'. So that I found -
Peter Jackson
UK
United Kingdom
London
...
...
I am not so well known with string splitting. I only know how to split string when they are only separated by a single character (eg - string1-string2-string3-....).

You should use regex for this.
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher results = p.matcher("[Peter Jackson] [UK] [United Kingdom] [London]....");
while (results.find()) {
System.out.println(results.group(1));
}

You can use this regex:
\\[(.+?)\\]
And the captured group will have your content.
Sorry for not adding the code. I don't know java

Is each item separated by spaces? if so, you could split by "\] \[" then replace all the left over brackets:
String vals = "[Peter Jackson] [UK] [United Kingdom] [London]";
String[] list = vals.split("\\] \\[");
for(String str : list){
str = str.replaceAll("\\[", "").replaceAll("\\]", "");
System.out.println(str);
}
Or if you want to avoid a loop you could use a substring to remove the beginning and ending brackets then just separate by "\\] \\[" :
String vals = " [Peter Jackson] [UK] [United Kingdom] [London] ";
vals = vals.trim(); //removes beginning whitspace
vals = vals.substring(1,vals.length()-1); // removes beginning and ending bracket
String[] list = vals.split("\\] \\[");

Try to replace
String str = "[Peter Jackson] [UK] [United Kingdom] [London]";
str = str.replace("[", "");
str = str.replace("]", "");
And then you can try to split it.

Splitting on "] [" should sort you, as in:
\] \[
Debuggex Demo
After this, just replace the '[' and the ']' and join using newline.

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 split a string into two parts on specific delimeter

I have a string "Rush to ER/F07^e80c801e-ee37-4af8-9f12-af2d0e58e341".
I want to split it into 2 strings on the delimiter ^. For example string str1=Rush to ER/F07 and String str2 = e80c801e-ee37-4af8-9f12-af2d0e58e341
For getting this i am doing splitting of the string , I followed the tutorial on stackoverflow but it is not working for me , here is a code
String[] str_array = message.split("^");
String stringa = str_array[0];
String stringb = str_array[1];
when I am printing these 2 strings I am getting nothing in stringa and in stringb I am getting all the string as it was before the delimiter.
Please help me
You have to escape special regex sign via \\ try this:
String[] str_array = message.split("\\^");
It is because the .split() method requires a regex pattern. Escape the ^:
String[] str_array = message.split("\\^");
You can get more information on this at http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-.

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

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];

Splitting Java string with quotation marks [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you recommend a Java library for reading (and possibly writing) CSV files?
I need to split the String in Java. The separator is the space character.
String may include the paired quotation marks (with some text and spaces inside) - the whole body inside the paired quotation marks should be considered as the single token.
Example:
Input:
token1 "token 2" token3
Output: array of 3 elements:
token1
token 2
token3
How to do it?
Thanks!
Split twice. First on quotes, then on spaces.
Assuming that the other solutions will not work for you, because they do not properly detect matching quotes or ignore spaces within quoted text, try something like:
private void addTokens(String tokenString, List<String> result) {
String[] tokens = tokenString.split("[\\r\\n\\t ]+");
for (String token : tokens) {
result.add(token);
}
}
List<String> result = new ArrayList<String>();
while (input.contains("\"")) {
String prefixTokens = input.substring(0, input.indexOf("\""));
input = input.substring(input.indexOf("\"") + 1);
String literalToken = input.substring(0, input.indexOf("\""));
input.substring(input.indexOf("\"") + 1);
addTokens(prefixTokens, result);
result.add(literalToken);
}
addTokens(input, result);
Note that this won't handle unbalanced quotes, escaped quotes, or other cases of erroneous/malformed input.
import java.util.StringTokenizer;
class STDemo {
static String in = "token1;token2;token3"
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, ";");
while(st.hasMoreTokens()) {
String val = st.nextToken();
System.out.println(val);
}
}
}
this is easy way to string tokenize

Categories

Resources