…当我的代码中的String变量将它们存储在自己中时,它们看起来像这样的“\”String\“”和“\”char\“”。。。
…我想使用java regex来区分它们,并在不包含所有“”和“”的情况下获得char和string的值。。。
您可以使用
环顾四周
语法来断言这些值。
这将产生重叠的值。
例如在文本中,
"abc" + x + "123"
这个
" + x + "
将被捕获。
((?<=\").+?(?=\")|(?<=').+?(?='))
以下是使用
Pattern
和
Matcher
班
String s = "123 \"abc\" 456 def '7'89";
Pattern p = Pattern.compile("((?<=\").+?(?=\")|(?<=').+?(?='))");
Matcher m = p.matcher(s);
while (m.find()) System.out.println(m.group(1));
输出
abc
7
或者,捕获引号,消除重叠值,并以编程方式删除基准。
(\".+?\"|'.+?')
String s = "123 \"abc\" 456 def '7'89", g;
Pattern p = Pattern.compile("(\".+?\"|'.+?')");
Matcher m = p.matcher(s);
while (m.find()) {
g = m.group(1);
System.out.println(g.substring(1, g.length() - 1));
}