使用Java Pattern和Matcher搜索包含正斜杠等标点符号的模式

时间:2012-07-24 15:31:23

标签: java regex pattern-matching

我有一个这样的字符串:1/80% of all goods sold for $44 million dollars or more/90/55 所以基本上我会有一个带有模式的字符串:

  

“某些数字”“正斜线”“包含正斜杠的任何标点符号的一些文字”“正斜杠”“某些数字”“正斜杠”“某些数字”

我不能在正斜杠上使用stringtokenizer和tokenize,因为我的文本块可能包含正斜杠。我非常擅长在java中使用模式和匹配器。关于我如何做到这一点的任何线索?或者可能有用的教程?在此先感谢!

4 个答案:

答案 0 :(得分:1)

这个正则表达式应该这样做:

^(\d+)\/(.*?)\/(\d+)\/(\d+)$

演示:http://www.rubular.com/r/ZIhe8iE0L0

答案 1 :(得分:0)

也许这可以作为正则表达式:

^\d+/.*/\d+/\d+$

根据需要添加捕获组。只要文本不包含换行符,这就应该有效。

答案 2 :(得分:0)

您正在寻找#/#< text> /#/#

以下是一些应该有效的代码:

    String toScan = "Did you know that 1/80 of all goods sold for $44 million or more/90/55? It's cool, because 1/5 of all people can type /1/2 like that.";
    String regexp = "[0-9]{1,}/[0-9]{1,}.{1,}?/[0-9]{1,}/[0-9]{1,}";
    Pattern pattern = Pattern.compile(regexp);
    Matcher m = pattern.matcher(toScan);
    while(m.find())
        System.out.println(m.group());

答案 3 :(得分:0)

这是一个简单的测试

import java.util.regex.*;

class RTest
{
public static void main(String[] args)
{
    String test1 = "1/80% of all goods sold for $44 million dollars or more/90/55";
    String test2 = "1/80% of all goods sold for $44 /million dollars or more/90/55";

    String patternStr = "(.*?)/(.*)/(.*?)/(.*?)$";
    Pattern pattern = Pattern.compile(patternStr);

    System.out.println("Test1...");
    // Test 1
    Matcher matcher = pattern.matcher(test1);
    boolean matchFound = matcher.find();

    if (matchFound)
    {
        for (int i = 0; i<=matcher.groupCount(); i++)
        {
            System.out.println(matcher.group(i));
        }
    }

    System.out.println("Test2...");
    // Test 2
    matcher = pattern.matcher(test2);
    matchFound = matcher.find();

    if (matchFound)
    {
        for (int i = 0; i<=matcher.groupCount(); i++)
        {
            System.out.println(matcher.group(i));
        }
    }       
}

}