获取每行的值 Java

huangapple go评论68阅读模式
英文:

Get value in each line Java

问题

我有一个字符串,每一行都有一个带标签的值,如何提取这些值?

我的字符串:

abi: armeabi-v7a
processor: 0
Processor: ARMv7 Processor rev 4 (v7l)
model name: ARMv7 Processor rev 4 (v7l)
BogoMIPS: 14.47
Features: half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32
CPU implementer: 0x41
CPU architecture: 7
CPU variant: 0x0
CPU part: 0xd03
CPU revision: 4

类似这样的内容我有很多,我想从每个标签中获取每个值,比如CPU part标签,我需要获取0xd03。我应该如何做到这一点?

英文:

I have a String, in each line there is a value with tag, how can I extract it?

My string : -

abi: armeabi-v7a
processor	: 0
Processor	: ARMv7 Processor rev 4 (v7l)
model name	: ARMv7 Processor rev 4 (v7l)
BogoMIPS	: 14.47
Features	: half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 
CPU implementer	: 0x41
CPU architecture: 7
CPU variant	: 0x0
CPU part	: 0xd03
CPU revision	: 4

Like this I have many, I want to get each value from each tag, like CPU part tag I need to get 0xd03. How can I do that?

答案1

得分: 3

如果您只是想,例如,打印出所有标签,您可以尝试在CR?LF上拆分字符串,然后再次使用拆分来隔离每行右侧的值。

String input = "abi: armeabi-v7a\n" +
               "processor   : 0\n" +
               "Processor   : ARMv7 Processor rev 4 (v7l)";
String[] lines = input.split("\\r?\\n");
for (String line : lines) {
    String[] parts = line.split("\\s*:\\s");
    System.out.println("key=" + parts[0] + ", value=" + parts[1]);
}

这将打印出给定的三行输入:

key=abi, value=armeabi-v7a
key=processor, value=0
key=Processor, value=ARMv7 Processor rev 4 (v7l)
英文:

If you just want to, for example, print out all tags, you could try splitting the string on CR?LF, then using split again to isolate the value on the RHS of each line.

String input = "abi: armeabi-v7a\n" +
               "processor   : 0\n" +
               "Processor   : ARMv7 Processor rev 4 (v7l)";
String[] lines = input.split("\r?\n");
for (String line : lines) {
    String[] parts = line.split("\\s*:\\s");
    System.out.println("key=" + parts[0] + ", value=" + parts[1]);
}

This prints, for the 3 line input given above:

key=abi, value=armeabi-v7a
key=processor, value=0
key=Processor, value=ARMv7 Processor rev 4 (v7l)

答案2

得分: 2

这是一个简单的算法。

  1. 通过 \n 分割字符串 => splitString
  2. 对 splitString 进行 : 分割 => keyValues
  3. 将 keyValues 的第一部分和第二部分作为 HashMap 的键和值以便于访问,或者你可以直接打印这些值。
英文:

Here's a simple algorithm.

  1. Split the string by \n => splitString
  2. Split splitString by : => keyValues
  3. Put the first part and second part of keyValues as keys and values of a HashMap for ease of access, or you could simply print the values.

huangapple
  • 本文由 发表于 2020年9月30日 14:31:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64132048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定