简体   繁体   English

使用正则表达式从字符串中读取多个变量

[英]Read multiple variables from a string using regex

I'm trying to split a string into different variables. 我正在尝试将字符串拆分为不同的变量。 Something like the opposite of String.format() . 类似于String.format() I want a particular regex to match and then that portion of the string should be assigned to a specific variable. 我希望匹配一个特定的正则表达式 ,然后将字符串的那一部分分配给特定的变量。 Is that possible using StringReader or any other class? 使用StringReader或任何其他类可能吗?

Example my String is 5 13-DEC-2010 16:47 A Tach 220 380 now it should be assigned to variables like: 例如,我的字符串是5 13-DEC-2010 16:47 A Tach 220 380现在应将其分配给以下变量:

  1. number = 5
  2. date = 13-DEC-2010
  3. time = 16:47
  4. type = A Tach
  5. num1 = 220
  6. num2 = 380

where all variables can be strings 所有变量都可以是字符串

Try this: 尝试这个:

var s = '5 13-DEC-2010 16:47 A Tach 220 380';
var re = /(\d+)\s+(\d{1,2}-[A-Z]{3}-\d{4})\s+(\d{2}:\d{2})\s+([\w\s+]*)\s+(\d+)\s+(\d+)/
var m = s.match(re);

Base from my past experience, there wasn't any builtin class that will do that. 根据我过去的经验,没有任何内置类可以做到这一点。 Just manually manipulate your data. 只需手动操作您的数据即可。 Like split it (str.split("\\s");), then stored in they respective variables. 像split(str.split(“ \\ s”);)一样,然后将它们分别存储在变量中。 But the problem is the case "A Tach". 但是问题是“ A Tach”。

If you ask me I'll just replace the data seperator(in your case its a space) with a regex that will not occur in your string, something like ";=;" 如果您问我,我将用分隔符替换数据分隔符(在您的情况下为空格),例如“; =;” where your string will be transformed into "5;=;13-DEC-2010;=;16:47;=;A Tach;=;220;=;380" Then just split the data and parse it to their respective variable. 其中您的字符串将被转换为“ 5; =; 13-DEC-2010; =; 16:47; =; A Tach; =; 220; =; 380”然后只需拆分数据并将其解析为各自的变量。

public static void main(String[] args) {
    String s = "5 13-DEC-2010 16:47 A Tach 220 380";
    String re = "(\\d+)\\s+(\\d{1,2}-[A-Z]{3}-\\d{4})\\s+(\\d{2}:\\d{2})\\s+([\\w\\s+]*)\\s+(\\d+)\\s+(\\d+)";
    Pattern p = Pattern.compile(re);
    String number=null,date=null,time=null,type=null,num1=null,num2=null;
    Matcher m = p.matcher(s);
    if (m.matches()) {
        number = m.group(1);
        date = m.group(2);
        time = m.group(3);
        type = m.group(4);
        num1 = m.group(5);
        num2 = m.group(6);
    }
    System.out.println(number);
    System.out.println(date);
    System.out.println(time);
    System.out.println(type);
    System.out.println(num1);
    System.out.println(num2);
}

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

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