sorry for the inaccurate Title, but i didn't know how to put it.
If my string would look like this:
1+"."+2+"abc"+3+","+12+"."
and I would like to get an array containing only the content between the "quotes"
.
abc
,
.
I would like to receive the above array.
How can i accomplish that?
Note: all values are random, only the double quotes are certain.
Example: string can also look like this:
23412+"11"+244+"11"+abc+"11"
result should be:
11
11
11
or
abc+"abc"+abcd+"abcd"
result should be:
abc
abcd
or
1+"."+2+"."+"."+"3"
result should be:
.
.
.
I hope that you can help.
Use this regex :
public static void main(String[] args) {
String s = "23412+\"11\"+244+\"11\"+abc+\"11\"\"abcd\"pqrs";
Pattern p = Pattern.compile("\"(.*?)\""); \\ lazy quantifier
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1));
}
}
O/P :
11
11
11
abcd
I know you want regex, but if you can also do it without regex:
public static void main(String[] args) {
String yourString = "23412+\"11\"+244+\"11\"+abc+\"11\"";
String result = "";
String[] splitted = yourString.split("\"");
if (splitted.length > 0) {
for (int i = 1; i < splitted.length; i += 2) {
result += splitted[i] + System.lineSeparator();
}
result = result.trim();
}
System.out.println(result);
}
You can use StringBuilder
for long strings.
I think it is very simple to write a method that does that and use it as a utility in your program... here's an example:
import java.util.ArrayList;
public class Test
{
public static void main(String[] args)
{
String str = "23412+\"11\"+244+\"11\"+abc+\"11\"\"abcd\"pqrs";
int i=0;
ArrayList<String> strList = new ArrayList<String>();
while (i<str.length())
{
if(str.charAt(i) == '\"')
{
int temp = i;
do
{
i++;
}
while (str.charAt(i) != '\"');
strList.add(str.substring(temp+1, i));
}
i++;
}
for(int j=0; j<strList.size(); j++)
{
System.out.println(strList.get(j));
}
}
}
you can change it to return the ArrayList instead of printing it and then you have the perfect utility to do the job
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.