简体   繁体   English

在java中解析这个字符串的最佳方法?

[英]Best way to parse this string in java?

I have a string that is the form of: 我有一个字符串形式:

{'var1':var2}

I was able to parse this string so that var1 and var2 are both string variables. 我能够解析这个字符串,以便var1和var2都是字符串变量。 However it takes multiple string tokenizer calls, first to split from the ":" and then to extract the data. 然而,它需要多个字符串标记化器调用,首先从“:”拆分然后提取数据。

So what would be the best (least lines of code) to do this? 那么最好的(最少的代码行)是什么呢?

If you just want an array containing the two values, then you can can do it in two lines by extracting a substring and then splitting on "':". 如果你只想要一个包含这两个值的数组,那么你可以通过提取子字符串然后拆分“':”来分两行完成。 It would end up looking something like this: 它最终会看起来像这样:

s = s.substring(2, s.length()-1);
String[] sarr = s.split("':");

If you really wanted a single line of code, you could combine them into: 如果您真的想要一行代码,可以将它们组合成:

String[] sarr = s.substring(2, s.length()-1).split("':");

This should work: 这应该工作:

String yourstring = "{'var1':var2}";
String regex = "\\{'(.+)':(.+)}";
Matcher m = Pattern.compile(regex).matcher(yourstring);
String var1 = m.group(1);
String var2 = m.group(2);

EDIT : for the commentators: 编辑 :评论员:

String: 串:

{'this is':somestring':more stuff:for you}

Output: 输出:

var1 = this is':somestring
var2 = more stuff:for you

PS: tested with Perl, don't have Java at hand right now, sorry. PS:用Perl测试,现在手头没有Java,抱歉。

EDIT: looks like Java regex engine does not like { unescaped as user unknown points out. 编辑:看起来像Java正则表达式引擎不喜欢{转义为用户未知指出。 Escaped it. 逃脱了它。

This is unsolvable in the general case. 在一般情况下,这是无法解决的。 Consider for example: 考虑例如:

case a) 案例a)

var1= VAR1 =

:':':

var2= VAR2 =

':'

The the full original string would be 完整的原始字符串将是

{':':':':':'}

case b) var1= 案例b)va​​r1 =

:

var2= VAR2 =

':':':'

the the full original string would be 完整的原始字符串

{':':':':':'}

So, we need "more information". 所以,我们需要“更多信息”。 Depending on your requirements / use case you had to live with the ambiguity, put limitations on the strings, or escape/encode the strings. 根据您的要求/用例,您必须忍受歧义,对字符串进行限制,或者对字符串进行转义/编码。

Something like (fragile - see comment(s)) : (脆弱 - 见评论)

// 3 lines..
String[] parts = "{'var1':var2}  ".trim().split("':");
String var1 = parts[0].substring(2,parts[0].length);
String var2 = parts[1].substring(0,parts[1].length-1);

You can use regex: 你可以使用正则表达式:

String re = "\\{'(.*)':(.*)}";
String var1 = s.replaceAll (re, "$1");
String var2 = s.replaceAll (re, "$2");

You need to mask the opening { , else you get an java.util.regex.PatternSyntaxException: Illegal repetition 你需要屏蔽开头{ ,否则你得到一个java.util.regex.PatternSyntaxException:非法重复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM