Reputation: 821
I am trying to use string split to solve my problem, but my program is only partially right. I am new to regex and still trying to understand how to implement it for complicated patterns.
I have below mentioned string formats:
String a = Internal module control "memory" sensor
String b = Internal module control memory "sensor"
String c = "Internal" module control "memory" sensor
The output I expect should be like:
String a = Internal module control "memory"/memory //(with or without quotes is fine)
String b = Internal module control memory "sensor"/sensor //(both are fine)
String c = "Internal"/Internal module control "memory"/memory //(here also both are fine)
What I tried:
My program works perfectly fine for String a
and String c
, but when I come across case like mentioned in String b
it fails.
String[] words = a.split("\"");
for (int i=0; i<words.length-1; i++) {
final_desc += words[i];
}
my o/p for a
, b
and c
is:
a = Internal module control memory
(fails) I expect: b = Internal module control memory sensor // I get b = Internal module control memory
c = Internal module control memory
P.S.
In general, I want to remove everything after last quote no matter how many quotes there are in the given string and if there are quotes in the last word then it should consider that word also, like presented in String b
Upvotes: 1
Views: 147
Reputation: 151
Try to use the replace()
method of the String.
Remove this block
String[] words = a.split("\"");
for (int i=0; i<words.length-1; i++) {
final_desc += words[i];
}
and put on its place this code
int lastQuote = a.lastIndexOf("\"");
if(lastQuote > 0) {
final_desc = a.subString(0, lastQuote).replace("\"", "");
}else {
final_desc = a;
}
Upvotes: 1
Reputation: 10174
Use the other version of split
which takes an additional limit
argument.
So
replace
String[] words = b.split("\"");
with
String[] words = b.split("\"", -1);
reason
Here specifying a negative limit value will make split
apply the pattern as many times as possible and also not disregard the trailing empty strings. Read the Java docs for more information.
Upvotes: 1