例如,输入将如下所示:
AddItem rt456 4 12 BOOK “File Structures” “Addison-Wesley” “Michael Folk”
我想使用扫描仪读取所有内容并将其放入数组中。
喜欢:
info[0] = rt456
info[1] = 4
..
..
info[4] = File Structures
info[5] = Addison-Wesley
那么如何获取引号之间的字符串?
编辑:我的代码的一部分->
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读取不带引号的字符串。
通过使用REGEX AS解决
read.next("([^\"]\\S*|\".+?\")\\s*");
一种使用凌乱的正则表达式的替代方法:
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
我认为引号是您在问题“”而不是“”中键入引号时使用的引号,因此不需要转义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句