从字符串中查找子字符串

时间:2014-10-31 06:45:50

标签: java string substring

我有以下字符串:

Test: Testid #123123 - Updated

我想从这个字符串中找到子串123123

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

但是我希望找到这个子字符串,它应该在#和下一个空格之间找到id而不给出开始和结束索引。

感谢。

7 个答案:

答案 0 :(得分:2)

试试这个:

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

这将为您提供在#之后开始char的字符串,直到下一个空白。

答案 1 :(得分:2)

试试这个,

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);

或尝试使用正则表达式

答案 2 :(得分:1)

如果您的示例与您提供的示例一样简单,那么您将不需要使用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));
        }
    }
}

答案 3 :(得分:0)

只需将其拆分为#然后将结果拆分 - 您将得到正确的结果。

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

这可能会有所帮助..

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

答案 6 :(得分:0)

您可以使用以下代码获取&#39;#&#39;之间的值。和空间。

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