简体   繁体   中英

Java Get String Between Two Strings

want to ask how to get the "200" value with this type of pattern? I need the simplest and easiest way without adding extra dependency library. I don't want the substring(11, s.length() - 1) method.

~PHONE_IDX=200~PHONE_DD=100~PHONE_KK=50~

You can use regex to accomplish this, by searching for the ~PHONE_characters=digits pattern, like so:

String str = "~PHONE_IDX=200~PHONE_DD=100~PHONE_KK=50~";
Pattern p = Pattern.compile("~PHONE_(?<attribute>\\w+)=(?<value>\\d+)");
Matcher m = p.matcher(str);//matcher for string
while(m.find())
{
  System.out.println("Next group: "+m.group());
  System.out.println("Attribute: "+m.group("attribute"));
  System.out.println("Value: "+m.group("value"));
}

This code will output the following:

Next group: ~PHONE_IDX=200
Attribute: IDX
Value: 200
Next group: ~PHONE_DD=100
Attribute: DD
Value: 100
Next group: ~PHONE_KK=50
Attribute: KK
Value: 50

Using the standard Java library, there is a package java.util.regex that may have a viable solution.

Pattern p = Pattern.compile("~PHONE_IDX=([0-9]*)", int flags);
Matcher matches = p.matcher(input);
boolean isMatches = m.matches();

The parentheses will put the result you're looking for into a group which can be easily accessed without having to substring or iterate over the string again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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