【问题标题】:Read string format and fetch required irregular data读取字符串格式并获取所需的不规则数据
【发布时间】:2019-04-06 18:43:54
【问题描述】:

我有一个这样的字符串格式,它是

的输出
readAllBytes(new String(Files.readAllBytes(Paths.get(data))

来自文件

a+2  b+3 c+33 d+88 ......

我的情况是我想在c+" " 之后获取数据。 c 的位置不是恒定的,但 c 只出现一次。它可能发生在任何地方。我所需的值将始终仅在c+ 之后。值 33..... 的所需大小也不是恒定的。有人可以帮我提供最佳代码吗?我觉得这里需要用到集合。

【问题讨论】:

  • 您能否指定以下格式的示例:inputText:__,expectedResult:___?
  • 我的输入是 a+2 b+3 c+33 d+88,我需要的输出是基于 33

标签: java string arraylist collections split


【解决方案1】:

你可以使用这个正则表达式,它可以让你捕获你想要的数据,

c\+(\d+)

解释:

c+ 匹配一个文字 c 字符,后面紧跟一个 + char (\d+) 捕获您有兴趣捕获的下一个数字。

演示,https://regex101.com/r/jfYUPG/1

这是一个演示相同的java代码,

public static void main(String args[]) {
    String s = "a+2 b+3 c+33 d+88 ";
    Pattern p = Pattern.compile("c\\+(\\d+)");
    Matcher m = p.matcher(s);
    if (m.find()) {
        System.out.println("Data: " + m.group(1));
    } else {
        System.out.println("Input data doesn't match the regex");
    }
}

这给出了以下输出,

Data: 33

【讨论】:

  • String s = "sample=true properties=myproperties";模式 p = Pattern.compile("属性\\=(\\d+)");匹配器 m = p.matcher(s); if (m.find()) { System.out.println("数据:" + m.group(1)); } else { System.out.println("输入数据与正则表达式不匹配"); }.....我尝试了这种情况,但输入错误..
  • 是否要捕获出现在 properties= 旁边的数据?然后你需要这样写 properties=(\\w+) 你也不需要转义 = 字符。 \\d 仅用于捕获数字,其中 \\w 等于 [a-zA-Z0-9_]
  • 是的,谢谢,我明白了。但我需要的数据是 a.b.c 格式。从你提供的代码中,我得到“a”作为输入。我需要 a.b.c 作为输入
  • 好的,如果您要捕获的文本中有点,则使用此字符集 [a-zA-Z。] 如果您的文本包含数字,则将数字包含在 0-9 的集合中
  • 非常感谢...这意味着很多。我对这些东西非常陌生,感谢您的帮助和及时的回复。
【解决方案2】:

这段代码将c+ 之后的值提取到下一个空格,如果没有空格,则提取到字符串的末尾:

String str = "a+2  b+3 c+33 d+88 ";
String find = "c+";

int index = str.indexOf(" ", str.indexOf(find) + 2);
if (index == -1)
    index = str.length();
String result = str.substring(str.indexOf(find) + 2, index);
System.out.println(result);

打印

33

或在方法中:

public static String getValue(String str, String find) {
    int index = str.indexOf(find) + 2; 
    int indexSpace = str.indexOf(" ", index);
    if (indexSpace == -1)
        indexSpace = str.length();
    return str.substring(index, indexSpace);
}

public static void main(String[] args) {
    String str = "a+2  b+3 c+33 d+88 ";
    String find = "c+";

    System.out.println(getValue(str, find));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    相关资源
    最近更新 更多