【问题标题】:what is the regex for getting statuscode in java?在java中获取状态码的正则表达式是什么?
【发布时间】:2015-07-03 08:28:17
【问题描述】:

下面是我从服务器获取的字符串,我想获取状态码

program 40006932 version 1 protocol tcp NOT registered
Transient program number selected = 40006932
TRANS_NUM = 999999
errorCount = 0
descriptor_loop_length= 1
descriptor_loop_val= 8828256
result_type= (null)
r_d_type= (null)
StatusCode # 0 = 0

我正在遵循一种方法,首先我遍历每一行并检查StatusCode,然后我可以将其与= 拆分并可以获得状态码,但它们是实现上述输出的更简单方法吗?

【问题讨论】:

  • 更简单还是更高效?我会追求更高的效率,它似乎是你的。
  • @stribizhev 高效 :)

标签: java regex string status


【解决方案1】:

您可以搜索模式匹配:

public static void main(String[] args) {
    String test = "r_d_type= (null)\n" +
                  "StatusCode # 0 = 0";

    Pattern pattern = Pattern.compile("StatusCode.* = (\\d*)");

    Matcher matcher = pattern.matcher(test);

    if (matcher.find()) {
        System.out.println("status code: " + matcher.group(1));
    }
}

【讨论】:

  • 你能详细说明一下吗?
  • @Crazyjavahacking:我投反对票,不要详细说明。 regex101.com/r/uG8mQ0/1
  • Pattern p = Pattern.compile("^StatusCode.* = (\\d*)"); Matcher m = p.matcher(sentence); if (m.find()) { System.out.println(m.group()); } System.out.println("not found"); 它返回找不到上述字符串
  • 去掉开头的^.
猜你喜欢
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 2014-04-06
  • 2020-01-19
  • 2015-06-09
相关资源
最近更新 更多