Java拆分字符串并删除

时间:2015-11-11 16:23:28

标签: java regex parsing substring

我有一个String我需要搜索并基本上从中提取所有大于3位数的数字,并且还会在某一点拆分并且只从拆分前获取这些值。

这里是字符串

String str = "where filter_2_id = 20003 and (acceptable_flag is true or acceptable_flag is null)  and  filter_2_id IN (20003)  AND filter_5_id IN (50053, 50014)  AND filter_1_id IN ( 10000 )  AND filter_2_id IN ( 20000, 20001, 20002, 20003, 20004 )";

基本上String可能有也可能没有" AND filter_1_id ..."以及之后的所有内容,但我需要搜索并查看String是否包含该内容。如果确实如此,我想删除之后的任何内容。我正在使用正则表达式来解析数字,但我不需要1或2位数字。这是我做过的一个示例,但没有考虑拆分或删除1-2位数字。

public class FilterTest {
    public static void main(String args[]){
        doMagic();
    }

    public static void doMagic(){
        String str = "where filter_2_id = 20003 and (acceptable_flag is true or acceptable_flag is null)  and  filter_2_id IN (20003)  AND filter_5_id IN (50053, 50014)  AND filter_1_id IN ( 10000 )  AND filter_2_id IN ( 20000, 20001, 20002, 20003, 20004 )";
        //String parsedString = StringUtils.trimWhitespace(str);
        Pattern p = Pattern.compile("(\\d+)");
        Matcher m = p.matcher(str);

        List<String> numberList = new ArrayList<String>();

        if( m.find() ){
            do {
                String local = m.group();
                System.out.println(local);
                numberList.add(local);
            } while(m.find());
        }
    }
}

这是我现在得到的输出: 2 20003 2 20003 五 50053 50014 1 10000 2 20000 20001 20002 20003 20004

我需要这个: 20003 20003 50053 50014

2 个答案:

答案 0 :(得分:0)

您正在使用的正则表达式\\d+将查找一个或多个数字,这也是您获得单个数字的原因。 您需要将正则表达式更改为\\d{3}\\d*以查找3位或更多位数。

使用split将filter_1_id上的字符串拆分。然后在结果数组中使用第一个字符串。 String[] tokens = str.split("filter_1_id");

import java.util.regex.*;
import java.util.*;
import java.lang.*;
import java.io.*;

class FilterTest
{
    public static void main (String[] args) throws java.lang.Exception
    {
        doMagic();
    }

    public static void doMagic(){
        String str = "where filter_2_id = 20003 and (acceptable_flag is true or acceptable_flag is null)  and  filter_2_id IN (20003)  AND filter_5_id IN (50053, 50014)  AND filter_1_id IN ( 10000 )  AND filter_2_id IN ( 20000, 20001, 20002, 20003, 20004 )";
        //String parsedString = StringUtils.trimWhitespace(str);
        String[] tokens = str.split("filter_1_id");
        Pattern p = Pattern.compile("(\\d{3}\\d*)");
        Matcher m = p.matcher(tokens[0]);

        List<String> numberList = new ArrayList<String>();

        if( m.find() ){
            do {
                String local = m.group();
                System.out.println(local);
                numberList.add(local);
            } while(m.find());
        }
    }
}

答案 1 :(得分:0)

正则表达式

 \d{m,}   // allows numbers of having m or more digits.
 \d{m,n}  // allows numbers of between m and n digits.

对于您当前的问题,请使用

Pattern p = Pattern.compile("(\\d{3,})");
相关问题