简体   繁体   中英

get the substring using regular expression in java

I have set of string in below formats

Local Tax 02/07 02/14 -0.42

I want to split the above as three separate stings like

Local Tax
02/07 02/14
-0.42

I wrote the following code snippet

package com.demo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DemoClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String s ="Sales Tax 08/07 09/06 0.42";
        //String s1 = "Sales Tax 02/07 02/14 -1.02";
         Pattern pattern = Pattern.compile("^([a-zA-Z ]*) ([0-9]{2}/[0-9]{2} [0-9]{2}/[0-9]{2}) ([-[0-9]*.[0-9][0-9]|[0-9]*.[0-9][0-9]])");
         Matcher matcher = pattern.matcher(s);
         if (matcher.find()) {
             System.out.println("String Name::"+s);
             System.out.println(matcher.group(1));
             System.out.println(matcher.group(2));
             System.out.println(matcher.group(3));
        }    
    }
}

and I am getting output as

String Name::Sales Tax 08/07 09/06 0.42
Sales Tax
08/07 09/06
0

the matcher.group(3) should return 0.42 but it is displaying as 0. could some help me on this please.

. is a special character in Regular Expressions, which matches (almost) any character (see more info ). Escaping . would make your regex work just fine (I also simplified the last part by making the - optional (see more info )):

^([a-zA-Z ]*) ([0-9]{2}/[0-9]{2} [0-9]{2}/[0-9]{2}) (-?[0-9]*\\.[0-9][0-9])

See, also, this short demo .

这将给出0.42的响应。

Pattern pattern = Pattern.compile("^([a-zA-Z ]*) ([0-9]{2}/[0-9]{2} [0-9]{2}/[0-9]{2}) ([0-9]*.[0-9][0-9]|[0-9]*.[0-9][0-9])");

You can try this, provided your 3rd value always starts with a "-" sign.

        String test = "Local Tax 02/07 02/14 -0.42";
        Pattern pattern = Pattern.compile("((?<=\\p{Alpha})\\s(?=\\d))|((?<=\\d)\\s(?=-\\d))");
        String[] result = pattern.split(test);
        for (String partial: result) {
            System.out.println(partial);
        }

Edit If your third value is not necessarily negative, try this instead (same output):

        String test = "Local Tax 02/07 02/14 -0.42";
        Pattern pattern = Pattern.compile("((?<=\\p{Alpha})\\s(?=\\d))|((?<=\\d)\\s(?=\\p{Punct}?[\\d\\.]+?$))");
        String[] result = pattern.split(test);
        for (String partial: result) {
            System.out.println(partial);
        }

Output:

Local Tax
02/07 02/14
-0.42

您可以使用此正则表达式:

^([a-zA-Z ]*) (\\d{2}/\\d{2} \\d{2}/\\d{2}) (-?\\d+(?:\.\\d{2})?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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