Java Regex: extract a substring from a pattern occurring multiple times

Sorry, if this is a lame question, I am quite new to Java development and regex patterns.

Basically I have a long string which has multiple occurrences of substrings like InstanceId: i-1234XYAadsadd, and I want to extract out the i-1234XYAadsadd part in an ArrayList using regex. Please help with the correct regular expression here.

//instanceResultString is the actual string containing occurences of pattern
List<String> instanceIdList = new ArrayList<String>(); 
    Matcher matcher = Pattern.compile("InstanceId:[.]*,").matcher(instanceResultString);
    while(matcher.find())
        instanceIdList.add(matcher.group());

The only point here is that the strings you want to match are made of non-whitespace characters. The S pattern matches a non-whitespace char.

See this demo:

String instanceResultString = "InstanceId: i-1234XYAadsadd, More text: InstanceId: u-222tttt, dde InstanceId: i-8999UIIIgjkkd,";
List<String> instanceIdList = new ArrayList<String>();
Matcher matcher = Pattern.compile("InstanceId:s*(S+),").matcher(instanceResultString);
while(matcher.find())
    instanceIdList.add(matcher.group(1));
System.out.println(instanceIdList); // Demo line
// => [i-1234XYAadsadd, u-222tttt, i-8999UIIIgjkkd]

Where

  • InstanceId: - a literal InstanceId: text
  • s* - zero or more whitespaces
  • (S+) - Group 1 (we grab these contents with .group(1) ) capturing 1 or more (but as many as possible) non-whitespace symbols
  • , - a comma.
  • 链接地址: http://www.djcxy.com/p/87022.html

    上一篇: RGB值加法颜色混合算法

    下一篇: Java正则表达式:从多次出现的模式中提取子字符串