从字符串

问题描述:

查找子字符串我有以下字符串:从字符串

Test: Testid #123123 - Updated 

我想找到这个字符串的子123123

我试过了:<msg>.substring(15, 21);它给了我正确的结果。

但我想找到这个子字符串的方式,它应该找到#和下一个空间之间的ID没有给开始和结束索引。

谢谢。

试试这个:

s.substring(s.indexOf("#")+1, s.indexOf(" ", s.indexOf("#")+1)) 

这给你的字符串#,直到下一个空白之后开始的字符。

只需用#分割它,然后将结果拆分 - 您将得到正确的结果。

你试过int indexOf(int ch,int fromIndex)吗?您可以从给定索引搜索下一个空格。

http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

试试这个,

String text = "Test: Testid #123123 - Updated"; 
int startIndex = text.indexOf('#'); //Finds the first occurrence of '#' 
int endIndex = text.indexOf(' ',startIndex); //Finds the first occurrence of space starting from position of # 
String subString = text.substring(startIndex+1, endIndex); 
System.out.println(subString); 

或者尝试使用正则表达式

,这可能是有帮助的..

String temp="Test: Testid #123123 - Updated"; 
int _first=temp.indexOf("#"); 
int _last= temp.indexOf(" ", _first); 
String result=temp.substring(_first, _last); 

如果你的例子真的是为简单一个你给,那么你将不需要使用regular expressions 。但是,如果您的实际输入更复杂,那么正则表达式不会比尝试以聪明的方式分割字符串更麻烦。

import java.util.regex.*; 


public class Foo{ 
    public static void main(String[] args) { 
     String original = "Test: Testid #123123 - Updated"; 
      Pattern mypattern = Pattern.compile("#([0-9]*) "); 
     Matcher matcher = mypattern.matcher(original); 
     while (matcher.find()) { 
      System.out.println(matcher.group(1)); 
     } 
    } 
} 

您可以使用以下代码来获取'#'和空格之间的值。

String str = "Test: Testid #123123 - Updated"; 
str = str.substring(str.indexOf('#')+1, str.indexOf(' ', str.indexOf("#")+1)+1);