如何在Java中获取字符串中双引号之间的字符串 [英] How to get the string between double quotes in a string in Java
本文介绍了如何在Java中获取字符串中双引号之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,输入如下:
AddItem rt456 4 12 BOOK "File Structures" "Addison-Wesley" "Michael Folk"
我想使用扫描仪读取所有内容并将其放入数组中.
and I want to read all by using scanner and put it in a array.
喜欢:
info[0] = rt456
info[1] = 4
..
..
info[4] = File Structures
info[5] = Addison-Wesley
那么我怎样才能得到引号之间的字符串呢?
So how can I get the string between quotes?
我的代码的一部分->
public static void main(String[] args) {
String command;
String[] line = new String[6];
Scanner read = new Scanner(System.in);
Library library = new Library();
command = read.next();
if(command.matches("AddItem"))
{
line[0] = read.next(); // Serial Number
line[1] = read.next(); // Shelf Number
line[2] = read.next(); // Shelf Index
command = read.next(); // Type of the item. "Book" - "CD" - "Magazine"
if(command.matches("BOOK"))
{
line[3] = read.next(); // Name
line[4] = read.next(); // Publisher
line[5] = read.next(); // Author
Book yeni = new Book(line[0],Integer.parseInt(line[1]),Integer.parseInt(line[2]),line[3],line[4],line[5]);
}
}
}
所以我使用 read.next 来读取没有引号的字符串.
so I use read.next to read String without quotes.
通过使用正则表达式解决
SOLVED BY USING REGEX AS
read.next("([^\"]\\S*|\".+?\")\\s*");
推荐答案
使用凌乱正则表达式的替代方案:
An alternative using a messy regular expression:
public static void main(String[] args) throws Exception {
Pattern p = Pattern.compile("^(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+["](.*)["][\\s]+["](.*)["][\\s]+["](.*)["]");
Matcher m = p.matcher("AddItem rt456 4 12 BOOK "File Structures" "Addison-Wesley" "Michael Folk"");
if (m.find()) {
for (int i=1;i<=m.groupCount();i++) {
System.out.println(m.group(i));
}
}
}
打印:
AddItem
rt456
4
12
BOOK
File Structures
Addison-Wesley
Michael Folk
我假设引号是您在问题"而不是"中键入的引号,因此不需要对它们进行转义.
I assumed quotes are as you typed them in the question "" and not "", so they dont need to be escaped.
这篇关于如何在Java中获取字符串中双引号之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文