2011-11-14 66 views
0
的一部分

我的Java程序产生像如何提取字符串

Give input: 4+5 
4+5 = <<9>> 

显示< <之间的答案>>一组行作为输出。 我只想提取答案9.我该怎么做?我应该使用模式匹配吗?

+1

为什么在输出时需要提取它? –

+1

使用正则表达式。 Java在java.util.regex包中具有必需的类。 –

+1

你需要解析你自己的**程序的输出吗?为什么不直接在'9'上做一些有用的事情,然后计算呢? –

回答

2
String str = "<<9>>"; 

String prefix = "<<"; 
String postfix = ">>"; 

String answer = str.substring(prefix.length, str.indexOf(postfix)); 
3

下面是一些正则表达式来帮助

String answer = "<<9>>"; 
    Pattern pat = Pattern.compile("\\d+"); 
    Matcher mat = pat.matcher(answer); 
    mat.find(); 
    answer = mat.group(); 
    System.out.println(answer); 

如果字符串将始终以这种格式<<n>>,然后@Sid解决方案是更好,因为不需要正则表达式。