Java:在某个字符后从字符串中获取子字符串

时间:2015-03-23 21:24:30

标签: java

我有一个字符串

create table temp_username_current_timestamp.....

我想从中提取"temp_username_timestamp"。 有人可以给我一些帮助吗?

3 个答案:

答案 0 :(得分:1)

假设“temp_username_current_timestamp”未知且每次都有所不同,但您知道要提取的字词或特定字符,则应使用indexOf(String str):

String input = "create table temp_username_current_timestamp other params"
String precedes = "table";
String extracted;

//Get the index of the start of the word to extract
int startIndex = input.indexOf(precedes) + precedes.length;
//Check if the word we are looking for is even there
if(startIndex > -1){
    //Get the index of the next space character
    int endIndex = input.indexOf(" ", startIndex);

    //If there are more parameters following ignore them
    if(endIndex > -1){
        //Extract the parameter given the indexes found
        extracted = input.substring(startIndex, endIndex);  
    } else {
        //If we are at the end of the string just extract what remains
        extracted = input.substring(startIndex);
    }
}

答案 1 :(得分:1)

如果您真的想使用substrings

    String s = "create table temp_username_current_timestamp";
    int start = s.indexOf("temp");
    String t = s.substring(start, s.length()); // temp_username_current_timestamp
    int start2 = t.indexOf("_current");
    String u = t.substring(0, start2); // temp_username
    int start3 = t.indexOf("_timestamp");
    String v = t.substring(start3,t.length()); // _timestamp
    String result = u + v; // temp_username_timestamp
    System.out.println(result);

输出: temp_username_timestamp

答案 2 :(得分:0)

下面是Java中的正则表达式代码,用于查找以temp_username

开头的单词
public static void findWord() {
   String input = "create table temp_username_current_timestamp";
   String regex = "\\btemp_username[^\\s]*";
   Pattern pattern = Pattern.compile(regex);
   Matcher matcher = pattern.matcher(input);
   String result = "";
   if (matcher.find()) {
      result = matcher.group();
   }
   System.out.println("Found " + result);
}

打印:找到temp_username_current_timestamp