使用正则表达式查找一组+ JAVA

时间:2012-08-30 09:39:29

标签: java regex string

我有一个程序,我想在开头用一定数量的“+”来过滤字符串。 例如:

+++Adam is working very well. 
++Adam is working well. 
+Adam is doing OK. 

我如何只挑选每个特定情况(即只有一个加号,只有两个加号,只有三个加号)?我通常得到以+开头的任何东西。

我编译了以下正则表达式模式,但我只获得一次返回(通常是两次++)或全部:

public static String regexpluschar = "^\\Q+\\E{1}[\\w <]";
public static String regexpluspluschar = "^\\Q+\\E{2}[\\w <]";
public static String regexpluspluspluschar = "^\\Q+\\E{3}[\\w <]";
Pattern plusplusplus = Pattern.compile(regexpluspluspluschar);
Pattern plusplus = Pattern.compile(regexpluspluschar);
Pattern plus = Pattern.compile(regexpluschar);

然后我尝试使用Matcher类 - 我使用了.find()和.matches()但是没有得到我之后的结果(java + regex newbie alert here)。

Matcher matcherplusplusplus = plusplusplus.matcher(check);
Matcher matcherplusplus = plusplus.matcher(check);
Matcher matcherplus = plus.matcher(check);

//OK we have 3+'s
if ((matcherplusplusplus.find())==true){
System.out.println("Filtering 3 +s.");
System.out.println("filter is " + filter + " in the 3 + filter.");
String toChange = getItem(i);
setItemFiltered(i, toChange);
}

//OK - we have 2 +'s
if ((matcherplusplus.find())==true){
System.out.println("Filtering 2 +s.");
System.out.println("filter is " + filter + " in the 2 + filter.");
String toChange = getItem(i);
setItemFiltered(i, toChange);   
}

//OK - we have 1 +'s
if ((matcherplus.find())==true){
System.out.println("Filtering 1 +.");
System.out.println("filter is " + filter + " in the 1 + filter.");
String toChange = getItem(i);
setItemFiltered(i, toChange);   
}

对于非常好奇的人来说,上面的if是嵌入在一个围绕某些JTextField循环的for循环中。完整代码:http://pastebin.ca/2199327

2 个答案:

答案 0 :(得分:2)

为什么不简单:

public static String regexpluschar = "^\\+[\\w <]";
public static String regexpluspluschar = "^\\+{2}[\\w <]";
public static String regexpluspluspluschar = "^\\+{3}[\\w <]";

甚至

public static String regexpluschar = "^\\+[^\\+]";
public static String regexpluspluschar = "^\\+{2}[^\\+]";
public static String regexpluspluspluschar = "^\\+{3}[^\\+]";

编辑:它正在处理我的测试程序,但我不得不删除您的特定代码:

String toChange = getItem(i);
setItemFiltered(i, toChange);

证明:我的输出是:

Filtering 3 +s.
+++Adam is working very well.  is in the 3 + filter.
Filtering 2 +s.
++Adam is working well.  is in the 2 + filter.
Filtering 1 +.
+Adam is doing OK.  is in the 1 + filter.

您的过滤器正在运行,但您的特定代码可能不会......(可能请查看setItemFiltered?)

答案 1 :(得分:1)

我认为这样的事情会更容易:

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("^(\\+{1,3}).*");

    Matcher matcher = pattern.matcher(<your text>);
    if (matcher.matches()) {
        String pluses = matcher.group(1);
        switch (pluses.length()) {

        }
    }

}

如果您想确保++++This is insane不匹配,请将模式更改为

Pattern pattern = Pattern.compile("^(\\+{1,3})[^+].*");