我正在研究一个项目,我不知道如何正确解析一些输入,例如a1 =(“hello”+“World”)。 a1是我制作的一个单元格,我最终试图将helloworld放入该单元格。这是我使用解析输入的类之一。当我使用数字时,它可以正常工作,但不能使用字符串。我只是想把一个像(“hi”+“man”)这样的输入解析为himan。我只是希望能够解析空格和加号,并将himan变成单个字符串。
import java.util.Scanner;
public class ParseInput {
private static String inputs;
static int col;
private static int row;
private static String operation;
private static Value field;
public static void parseInput(String input){
//splits the input at each regular expression match. \w is used for letters and \d && \D for integers
inputs = input;
Scanner tokens = new Scanner(inputs);
String[] strings = input.split("=");
String s1 = strings[0].trim(); // a1
String s2 = strings[1].trim(); // "Hello" + "World"
strings = s2.split("\\+");
String s3 = strings[0].trim().replaceAll("^\"", "").replaceAll("\"$", ""); // Hello
String s4 = strings[1].trim().replaceAll("^\"", "").replaceAll("\"$", ""); // World
String field = s3 + s4;
String colString = s1.replaceAll("[\\d]", ""); // a
String rowString = s1.replaceAll("[\\D]", ""); // 1
int col = colString.charAt(0) - 'a'; // 0
int row = Integer.parseInt(rowString);
TextValue fieldvalue = new TextValue(field);
Spreadsheet.changeCell(row, col, fieldvalue);
String none0 = tokens.next();
@SuppressWarnings("unused")
String none1 = tokens.next();
operation = tokens.nextLine().substring(1);
String[] holder = new String[2];
String regex = "(?<=[\\w&&\\D])(?=\\d)";
holder = none0.split(regex);
row = Integer.parseInt(holder[1]);
col = 0;
int counter = -1;
char temp = holder[0].charAt(0);
char check = 'a';
while(check <= temp){
if(check == temp){
col = counter +1;
}
counter++;
check = (char) (check + 1);
}
System.out.println(col);
System.out.println(row);
System.out.println(operation);
setField(Value.parseValue(operation));
Spreadsheet.changeCell(row, col, fieldvalue);
}
public static Value getField() {
return field;
}
public static void setField(Value field) {
ParseInput.field = field;
}
}
答案 0 :(得分:0)
如果你试图删除空格,那就是单行...
input = input.replaceAll("[\\s+\"]", "");
另一种方法是简单地删除所有&#34;非单词&#34;字符(定义为0-9,a-z,A-Z和下划线):
input = input.replaceAll("\\W", "");
答案 1 :(得分:-1)
使用StringBuilder
。 String
在Java中是不可变的,这意味着每次要组合两个字符串时,您将创建一个新实例。使用append()
方法(几乎可以接受任何内容)将内容添加到最后。
StringBuilder input = "";
input.append("hel").append("lo");
Here是它的文档。看一看。