简体   繁体   English

将字符串拆分为单词并加倍

[英]Splitting a string into words and doubles

I am writing a program to read a file that looks like this: 我正在编写一个程序来读取一个看起来像这样的文件:

NODE: label Buenous Aires:x=131.3456:y=-48.783 节点:标签Buenous Aires:x = 131.3456:y = -48.783

I want the program to split each line into an array with the entries of the label, then the x value, and the y value. 我希望程序将每一行拆分为带有标签条目的数组,然后是x值和y值。 I have looked into using the s.split tool with regular expressions but I do not know how to store the information that I am reading in into the program. 我已经研究过将s.split工具与正则表达式一起使用,但是我不知道如何将正在阅读的信息存储到程序中。

String[] words=s.split(" ");
"NODE: label=(.+):x=(\d+):y=(\d+)";

Could someone please give me tips on how to make such an array. 有人可以给我提示如何制作这样的数组。 I am looking for the array to have 3 entries, the first the label Buenous Aires, the second the x value and the third the y value. 我正在寻找具有3个条目的数组,第一个标签为Buenous Aires,第二个为x值,第三个为y值。

If you're not comfortable with regex, you could instead 如果您对正则表达式不满意,可以改用

  1. Split on colons 在冒号上分割
  2. Loop over those strings (start at position 1) 循环遍历这些字符串(从位置1开始)
  3. Split on equal signs 等号分裂
  4. Extract your data 提取数据

If you want to use split() (which is a good idea, since it can directly yield the wanted string array), you have not to specify the overall pattern of the string like you intended with "NODE: label=(.+):x=(\\d+):y=(\\d+)" , but only a delimiting expression, as :.= : 如果要使用split() (这是个好主意,因为它可以直接产生所需的字符串数组),则不必像预期的那样使用"NODE: label=(.+):x=(\\d+):y=(\\d+)"来指定字符串的整体模式"NODE: label=(.+):x=(\\d+):y=(\\d+)" ,但仅是一个定界表达式,如:.=

  • : - ends the previous entry : -结束上一个条目
  • . - matches x or y -匹配xy
  • = - preludes the next entry = -前一个下一个条目

    String s = "NODE: label=Buenous Aires:x=131.3456:y=-48.783";
    String[] words = s.substring(12).split(":.=");

The substring(12) skips the leading NODE: label= . substring(12)跳过前导NODE: label=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM