Java 使用引号内的引号进行命令解析
我尝试用Java正则表达式解析命令已有一段时间了,但没有成功。我遇到的主要问题是分隔符是空格,然后我想将双引号内的所有内容都视为参数,但如果其中一个参数在引号内包含引号,该怎么办。以下是命令和几个示例:Java 使用引号内的引号进行命令解析,java,regex,Java,Regex,我尝试用Java正则表达式解析命令已有一段时间了,但没有成功。我遇到的主要问题是分隔符是空格,然后我想将双引号内的所有内容都视为参数,但如果其中一个参数在引号内包含引号,该怎么办。以下是命令和几个示例: my_command "regex or text" <"regex or text"|NA> <"text or regex"|NA> integer integer Example1: my_command "Simple case" NA NA 2 3 Ex
my_command "regex or text" <"regex or text"|NA> <"text or regex"|NA> integer integer
Example1: my_command "Simple case" NA NA 2 3
Example2: my_command "This is it!" "[\",;']" "Really?" 3 5
Example3: my_command "Not so fast" NA "Another regex int the mix [\"a-zA-Z123]" 1 1
提前感谢您的帮助。尝试使用正则表达式执行此操作是错误的-您没有解析 从以下内容开始-您将使用正则表达式:
public void test() {
System.out.println(parse("\"This is it!\" \"[\\\",;']\" \"Really?\" 3 5"));
}
List<String> parse(String s) {
List<String> parsed = new ArrayList<String>();
boolean inQuotes = false;
boolean escape = false;
int from = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case ' ':
if (!inQuotes && !escape) {
parsed.add(s.substring(from, i));
from = i + 1;
}
break;
case '\"':
if (!escape) {
inQuotes = !inQuotes;
}
escape = false;
break;
case '\\':
escape = !escape;
break;
default:
escape = false;
break;
}
}
if (from < s.length()) {
parsed.add(s.substring(from, s.length()));
}
return parsed;
}
我使用了
^
来表示引号,并对引号中的所有字符使用了
。因此,在第一个引号之后没有进一步的拆分,因为之后没有未引号的空格。感谢您的快速回复,但这并不完全有效。尝试了以下内容:String str=“my_command\”Something[\'abc']\“\'text\'NA 11”。@user2182414-我现在得到了[my_command”,“Something['abc']”“text”NA 11],这是有意义的,因为所有空格都在第一个空格后加引号-你期待什么?注:我对\“
的大小写做了一些调整。我希望:list[0]=my\u命令,list[1]=Something[“abc],list[2]=text,list[3]=1,list[4]=1。使用上述方法,我得到的列表[0]=my_命令列表[1]=“Something[“abc']”text“NA 11但abc]后面的空格不应该是分隔符。引号内的空格不应该是分隔符。因此,例如,“Hello number 2”将计为一个参数/项,“Hello number\”2\“也将是一个参数。
public void test() {
System.out.println(parse("\"This is it!\" \"[\\\",;']\" \"Really?\" 3 5"));
}
List<String> parse(String s) {
List<String> parsed = new ArrayList<String>();
boolean inQuotes = false;
boolean escape = false;
int from = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case ' ':
if (!inQuotes && !escape) {
parsed.add(s.substring(from, i));
from = i + 1;
}
break;
case '\"':
if (!escape) {
inQuotes = !inQuotes;
}
escape = false;
break;
case '\\':
escape = !escape;
break;
default:
escape = false;
break;
}
}
if (from < s.length()) {
parsed.add(s.substring(from, s.length()));
}
return parsed;
}
String str = "my_command \"Something [\"abc']\" \"text\" NA 1 1";
// ............ .. .......
// ^ ^ ^ ^ ^