... When the String variable in my code stores them in itself they look something like this "\"string\"" and "\'char\'". ...个
... I want to use java regex to differentiate between them and get the value of the char and string without all the "" and ''. ...个
您可以使用look-around语法来断言这些值.
This will produce overlapping values.
For example in the text, "abc" + x + "123"
, the " + x + "
will be captured.
((?<=\").+?(?=\")|(?<=').+?(?='))
下面是使用100和101类的示例.
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));
}