2011-10-13 98 views
-5

可能重复:
How to check that the string contains the number format in Java?如何获取Java中两个数字之间的字符串?

可以说,我有以下格式的字符串:

string1 = "1. Stack Overflow 2. Google 3. Reddit" 

如何挑选出来的数字之间的子?

+0

-1显示绝对没有努力。 –

+0

@MattBall我第二。 – 0xCAFEBABE

+1

有些人不知道寻求帮助的正确方式,有些人在处理这个问题时有敌意。两种方法都同样无知。 – Bob

回答

2

您可以使用正则表达式和捕获组:

String str = "1. Stack overflow 2. Google"; 
Matcher m = Pattern.compile("\\d\\. (.*?) \\d").matcher(str); 

if (m.find()) 
    System.out.println(m.group(1)); // Prints "Stack overflow" 

IDEONE.com demo

+0

在m.group(1)这里“1”是指什么?如何获得google – naresh

+0

'm.group(1)'返回对应于'(。*?)'的匹配部分。如果你想在这个谷歌搜索*正则表达式捕获组*(或阅读例如[这里](http://download.oracle.com/javase/6/docs/api/java/util/regex/ )) – aioobe

1

的正则表达式匹配上面的例子是

\d+\.\s(\D+)\d\. 

转义为您提供方便。

这将捕获的数字(和点)之间的文本matchgroup的1

0

您可以用正则表达式做到这一点:

Pattern p = Pattern.compile("\\d+\\. (\\D+)\\d"); 
Matcher m = p.matcher(str); 
if (m.find()) 
    System.out.println(m.group(1)); 
+0

或在一行中:str.replaceAll(“^。*?\\ d + \\。”,“”).replaceAll(“\\ d。*”,“”) – Ramon

0

我不会做你的功课。你没有付出任何努力。看看这个简单的方法。在你的代码中实现它并进行修改,以便它符合你的问题。

public boolean isInteger(String input) 
    { 
     try 
     { 
      Integer.parseInt(input); 
      return true; 
     } 
     catch(Exception) 
     { 
      return false; 
     } 
    } 
4

尝试String.split()

String[] s = string.split("[0-9]+. ", String1); 

将产生数组:

{"Stack overflow ", "Google"} 

从中你,你可以随意选择字符串。为了更好,你可能需要trim()这个字符串。

+0

这里是什么STRING1? – naresh

+0

String1是你指定它在你的问题。 – Dave

0

字符串分割功能在这里工作也没关系:

String test = "1. Stack overflow 2. Google"; 
String[] test2 = test.split("\\d\\."); 
  • test2[0]" Stack overflow"
  • test2[1]将​​

您可以使用test2[0].trim()摆脱多余的空格。

相关问题