[英]Java - Split string based on space and single quote but ignore two single quotes
I want to split the string using space and single quote. 我想使用空格和单引号分隔字符串。 But two single quotes should be ignored. 但是应该忽略两个单引号。
Input: 输入:
name eq 'a''b'
Output should be: 输出应为:
name
eq
a''b
I tried to use 我尝试使用
[^\\s\"(?<!')'(?!')]+|\"[^\"]*\"|(?<!')'(?!')[^(?<!')'(?!')]*(?<!')'(?!')"
but it does not work. 但它不起作用。
The following one should suit your needs: 以下内容将满足您的需求:
'(?:[^']|'')+'|[^ ]+
Java example: Java示例:
String input = "foobar foo bar 'foobar' 'foo bar' 'foo''bar'";
Pattern pattern = Pattern.compile("'(?:[^']|'')+'|[^ ]+");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String match = matcher.group();
System.out.println(match);
}
Hi the actual regex is 嗨,实际的正则表达式是
"\\s|(?<!')'(?!')"
It produces output array as follows 它产生输出数组如下
[name, eq, , a''b]
This can be done without regex
too. 也可以不用regex
来完成。
String s = "name eq 'a''b'";
String[] split = new String[3];
Scanner in = new Scanner(s);
split[0] = in.next();
split[1] = in.next();
String temp = in.next();
split[2] = temp.substring(1,temp.length() - 1);
//test output
for(String x : split)
System.out.println(x);
This will print: 这将打印:
name
eq
a''b
If you need a more generic solution you need to provide more details. 如果您需要更通用的解决方案,则需要提供更多详细信息。
Hope this helps. 希望这可以帮助。
Here is how I would do: 这是我的做法:
String value = "name eq 'a''b'";
value = value.replaceAll(" '", " ").replaceAll("'$", "");
System.out.println(value);
String[] arr = value.split(" ");
You can try with Lookaround 您可以尝试环视
Pattern 图案
(?<!')'(?!')
Sample code: 样例代码:
System.out.println(Arrays.toString("name eq 'a''b'".split("(?<!')'(?!')")));
output: 输出:
[name eq , a''b]
Pattern explanation: 模式说明:
(?<! look behind to see if there is not:
' '\''
) end of look-behind
' '\''
(?! look ahead to see if there is not:
' '\''
) end of look-ahead
To split based on space or single quote use 要根据空间或单引号进行拆分,请使用
*(?<!')[ '](?!') *
sample code: 样例代码:
System.out.println(Arrays.toString("name eq 'a''b'".split(" *(?<!')[ '](?!') *")));
output: 输出:
[name, eq, a''b]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.