I am looking for a Java Regex, so that I can break the following expresion : first using '-', but if '-' is used in a quotation mark it shoul be ignored.
我正在寻找一个Java Regex,以便我可以打破以下表达式:首先使用' - ',但如果在引号中使用' - '则应该忽略它。
e.g: a test - which "contains "-"" inside - a quotation mark. result should be an arry like this:
例如:一个测试 - “包含” - “”里面 - 一个引号。结果应该是这样的arry:
[0]: a test
[1]: which "contains "-"" inside
[2]: a quotation mark
I am not really good with regular expression and will be thank full if anyone can help me :) thanks in advance
我对正则表达式并不是很好,如果有人可以帮助我,我会非常感谢:)提前感谢
2 个解决方案
#1
2
Check out Regex Planet to test out any regex's you make
查看Regex Planet以测试你所做的任何正则表达式
You should be able to achieve this with
你应该能够实现这一目标
String[] splitAray = yourString.Split("[^\"]-[^\"]")
Update using look ahead/behind so that the characters before and after - are not consumed
使用向前/向后更新以便不消耗前后的字符
String[] splitAray = yourString.Split("(?!\")-(?!\")")
#2
2
Solution using lookbehind and lookahead:
使用lookbehind和lookahead的解决方案:
String input = "a test - which \"contains \"-\" inside - a quotation mark";
String[] chunks = input.split("(?<!\")-(?!\")");
System.out.println(Arrays.toString(chunks));
OUTPUT:
[a test , which "contains "-" inside , a quotation mark]
EDIT: changing the first part of regexp ((?!\")
) to (?<!\")
编辑:将正则表达式的第一部分((?!\“))更改为(?
#1
2
Check out Regex Planet to test out any regex's you make
查看Regex Planet以测试你所做的任何正则表达式
You should be able to achieve this with
你应该能够实现这一目标
String[] splitAray = yourString.Split("[^\"]-[^\"]")
Update using look ahead/behind so that the characters before and after - are not consumed
使用向前/向后更新以便不消耗前后的字符
String[] splitAray = yourString.Split("(?!\")-(?!\")")
#2
2
Solution using lookbehind and lookahead:
使用lookbehind和lookahead的解决方案:
String input = "a test - which \"contains \"-\" inside - a quotation mark";
String[] chunks = input.split("(?<!\")-(?!\")");
System.out.println(Arrays.toString(chunks));
OUTPUT:
[a test , which "contains "-" inside , a quotation mark]
EDIT: changing the first part of regexp ((?!\")
) to (?<!\")
编辑:将正则表达式的第一部分((?!\“))更改为(?