两个字符串之间的子串选择

时间:2013-12-13 01:23:40

标签: java regex syntax substring

我正在做一些随机的Java工作,而我的应用程序会保存一个包含以下数据的文件:

Word: Word1 Description: Desc1 Type: 1 
Word: Word2 Description: Desc2 Type: 2 
Word: Word3 Description: Desc3 Type: 3 
Word: Word4 Description: Desc4 Type: 4 

它成功地保存了它,在尝试检索数据时,我无法找出应该应用的正则表达式过滤器。例如,从行:

    Word: Word1 Description: Desc1 Type: 1 

我想提取:

Word1
Desc1
1

每个人都在不同的字符串中。

我只是不了解模式语法,它已经给了我一个头脑。谢谢你的时间:))

-----------------编辑----------------

谢谢大家!我终于使用了Kon的答案。结果代码比我想象的要简单得多。我将代码留给任何可能遇到类似问题的人。

package resources;

import resources.manager.Word;

public class CommonFunctions {
public static Word parseString(String str){

    String[] stringA = str.split(" "); 

    Word result = new Word(stringA[1],stringA[3],Integer.parseInt(stringA[5]));
    return result;
}

public static String parseWord(Word wrd){
    //TODO
    return null;
    }
}

4 个答案:

答案 0 :(得分:1)

您似乎正在寻找:之后放置的字词或数字。您可以使用此正则表达式:\\s(\\w+)表示

  • :
  • \\s*零个或多个空格
  • (\\w+)一个或多个0-9a-zA-Z_类型的字符。同样用括号正则表达式围绕它将把这部分匹配放在group 1

演示:

String[] data = { "Word: Word1 Description: Desc1 Type: 1 ",
        "Word: Word2 Description: Desc2 Type: 2 ",
        "Word: Word3 Description: Desc3 Type: 3 ",
        "Word: Word4 Description: Desc4 Type: 4 " };
Pattern p = Pattern.compile(":\\s*(\\w+)");
for (String s:data){
    Matcher m = p.matcher(s);
    while (m.find())
        System.out.println(m.group(1));
}

OUTPT:

Word1
Desc1
1
Word2
Desc2
2
Word3
Desc3
3
Word4
Desc4
4

答案 1 :(得分:0)

此正则表达式适用于以上数据:

(\b\w+\b)(?!:)

这个正则表达式意味着什么:

  1. 开始捕获组(
    1. 匹配字边界\b
    2. 在1和无限次\w
    3. 之间匹配字母数字字符+
    4. 匹配字边界\b
  2. 关闭捕获组)
  3. 断言从这个位置开始不能匹配以下内容(?!(负向前瞻)
    1. 字符:字面意思
  4. 关闭否定前瞻)

答案 2 :(得分:0)

一个班轮:

String str = "Word: Word1 Description: Desc1 Type: 1";

// Output: ["Word1", "Desc1", "1"]
str.replaceFirst(" ?\\w*: ", "").split(" ?\\w*: ");

答案 3 :(得分:-1)

您可以使用StringTokenizer:

String str = "Word: Word1 Description: Desc1 Type: 1";
StringTokenizer st = new StringTokenizer(str," ");

st.nextToken();
String word = st.nextToken();
St.nextToken();
String description = st.nextToken();
st.nextToken();
String type = st.nextToken();