Reputation: 421
I have a string like this,
["[number][name]statement_1.","[number][name]statement_1."]
i want to get only statement_1
and statement_2
. I used tried in this way,
String[] statement = message.trim().split("\\s*,\\s*");
but it gives ["[number][name]statement_1."
and "[number][name]statement_2."]
. how can i get only statement_1
and statement_2
?
Upvotes: 2
Views: 183
Reputation: 70732
I somehow don't think that is your actual string, but you may try the following.
String s = "[\"[number][name]statement_1.\",\"[number][name]statement_2.\"]";
String[] parts = s.replaceAll("\\[.*?\\]", "").split("\\W+");
System.out.println(parts[0]); //=> "statement_1"
System.out.println(parts[1]); //=> "statement_2"
Upvotes: 2
Reputation: 41838
Match All instead of Splitting
Splitting and Match All are two sides of the same coin. In this case, Match All is easier.
You can use this regex:
(?<=\])[^\[\]"]+(?=\.)
See the matches in the regex demo.
In Java code:
Pattern regex = Pattern.compile("(?<=\\])[^\\[\\]\"]+(?=\\.)");
Matcher regexMatcher = regex.matcher(yourString);
while (regexMatcher.find()) {
// the match: regexMatcher.group()
}
In answer to your question to get both matches separately:
Pattern regex = Pattern.compile("(?<=\\])[^\\[\\]\"]+(?=\\.)");
Matcher regexMatcher = regex.matcher(yourString);
if (regexMatcher.find()) {
String theFirstMatch: regexMatcher.group()
}
if (regexMatcher.find()) {
String theSecondMatch: regexMatcher.group()
}
Explanation
(?<=\])
asserts that what precedes the current position is a ]
[^\[\]"]+
matches one or more chars that are not [
, ]
or "
(?=\.)
asserts that the next character is a dotReference
Upvotes: 3
Reputation: 3882
Use a regex instead.
With Java 7
final Pattern pattern = Pattern.compile("(^.*\\])(.+)?");
final String[] strings = { "[number][name]statement_1.", "[number][name]statement_2." };
final List<String> results = new ArrayList<String>();
for (final String string : strings) {
final Matcher matcher = pattern.matcher(string);
if (matcher.matches()) {
results.add(matcher.group(2));
}
}
System.out.println(results);
With Java 8
final Pattern pattern = Pattern.compile("(^.*\\])(.+)?");
final String[] strings = { "[number][name]statement_1.", "[number][name]statement_2." };
final List<String> results = Arrays.stream(strings)
.map(pattern::matcher)
.filter(Matcher::matches)
.map(matcher -> matcher.group(2))
.collect(Collectors.toList());
System.out.println(results);
Upvotes: 0
Reputation: 29
is the string going to be for example [50][James]Loves cake?
Scanner scan = new Scanner(System.in);
System.out.println ("Enter string");
String s = scan.nextLine();
int last = s.lastIndexOf("]")+1;
String x = s.substring(last, s.length());
System.out.println (x);
Enter string
[21][joe]loves cake
loves cake
Process completed.
Upvotes: 1