如何在Java中从String获取多个子字符串加上额外的数字?

时间:2015-05-26 10:32:29

标签: java regex

假设我们有以下字符串:

(form_component_34=="Yes"||case_attribute_37==3&&case_attribute_40?has_content)

我想要做的就是获得它的操作数:

  • form_component_34
  • case_attribute_37
  • case_attribute_40

它们总是以字符串" form_component _"开头。或" case_attribute _",并在其后面有一个数字(作为ID)。我假设我应该使用正则表达式。

你们中的任何人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

您可以使用以下正则表达式:

(?:form_component_|case_attribute_)\\d+

Java代码:

String str = "(form_component_34==\"Yes\"||case_attribute_37==3&&case_attribute_40?has_content)";
    Pattern r = Pattern.compile("(?:form_component_|case_attribute_)\\d+");
    ArrayList<String> matches = new ArrayList<String>(); 
    Matcher m = r.matcher(str);
    while (m.find())
    {
        matches.add(m.group());
    }
    System.out.println(matches);

输出:

[form_component_34, case_attribute_37, case_attribute_40]

请参阅org.springframework.core.io.UrlResource.getInputStream()

答案 1 :(得分:1)

这是代码。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatching
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "(form_component_34==\"Yes\"||case_attribute_37==3&&case_attribute_40?has_content)";
      String pattern = "(?:form_component_|case_attribute_)\\d+";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
       while(m.find()) {
         System.out.println(""+m.group());
      }
   }
}