Reputation: 47
~separate text fields~ and ^ separate all fields
String being inputed (fields can be empty)
~01001~^~0100~^~Butter, salted~^~BUTTER,WITH SALT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
My current split
String [] splited = str.split("\\^",-1);
for (String s : splited){
System.out.println (s);
}
Output
~01001~
~0100~
~Butter, salted~
~BUTTER,WITH SALT~
~~
~~
~Y~
~~
0
~~
6.38
4.27
8.79
3.87
How do change the regex so that ~~ are not included? (empty fields are fine)
What I want the output to be
01001
0100
Butter, salted
BUTTER,WITH SALT
Y
0
6.38
4.27
8.79
3.87
Empty lines should be ""
Upvotes: 0
Views: 1229
Reputation: 785058
Use this regex to match the data you want:
Pattern p = Pattern.compile("~([^~]*)~|([^\\^]+)");
and get the matched data using Matcher
API.
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.groupCount() == 2 ? m.grop(2) : m.grop(1));
}
Upvotes: 1
Reputation: 7057
It's unclear how ~ are treated, but it seems simple enough to just put both characters as a split character:
String b[] = str.split("[\\^~]");
Which essentially ignores all ~ and ^ characters.
Upvotes: 0
Reputation: 24802
Splitting won't be appropriate to get rid of those tildes. You will want either to replace ~(.*?)~
with \1
or to use basic detection (charAt
) and manipulation (subString
)
Upvotes: 0