简体   繁体   English

分割字符串并使用正则表达式从复杂字符串中获取值

[英]split string and get the value using regex from a complicated string

I have a string like this {"product_tags":"yin_yang,yin yang"} . 我有一个像这样的字符串{"product_tags":"yin_yang,yin yang"} what I want to do is just avoid everything else other than yin yang . 我想做的就是避免阴阳以外的一切。 There is two strings but I just want the first one. 有两个字符串,但我只想要第一个。

Note that in some cases even if the second string is not available I want to get the same result. 请注意,在某些情况下,即使第二个字符串不可用,我也希望得到相同的结果。 And that string might change so it is not necessary that the string will be always yin_yang sometimes it can be motorbike or anything else. 而且该字符串可能会更改,因此不必总是将字符串设为yin_yang有时也可以是motorbike或其他任何东西。

It Look like JSON String Use the JSONParser in java 看起来像JSON字符串在Java中使用JSONParser

JSONObject jobject=new JSONObject(STRING);
String value=jobject.getString("product_tags");

EDITED EDITED

Using REGEX 使用正则表达式

 String json="{\"product_tags\":\"yin_yang,yin yang\"}";
    json=json.replaceAll("([{}]+)", "");
    String value[]=json.split(":");
    System.out.print(value[1]);

You can use StringTokenizer to parse your string 您可以使用StringTokenizer解析您的字符串

String str ="{\"product_tags\":\"yin_yang,yin yang\"}";
StringTokenizer to = new StringTokenizer(str,":}");
while(to.hasMoreTokens()){
    String firstString = (String) to.nextElement();
    String secondString = (String) to.nextElement();
System.out.print(secondString);
}

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

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