java提取地址项由正则表达式

时间:2011-03-21 20:33:04

标签: java regex

我有一个字符串: 用户1:password@192.168.1.3:3306 / dbname1 我需要填写用户名,密码,主机,端口和dbname变量... 我的代码:

String patternStr = "(\b[A-Z0-9._%+-]+):([A-Z]+)@([A-Z0-9.-]+):([0-9]{1,5})/([A-Z0-9_-]+)";
Pattern p = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(dbpath);
System.out.println(matcher.matches());

输出:

false

:(请告诉我我的错误... 谢谢。

4 个答案:

答案 0 :(得分:4)

这是一个更简单的版本,它不是100%正确的,但它会在你的情况下完成工作:

String dbpath = "user1:password@192.168.1.3:3306/dbname1";
String patternStr = "([^:]+):([^@]+)@([^:]+):([^/]+)/(.+)";
Pattern p = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(dbpath);
System.out.println(matcher.matches());

// Output: true

答案 1 :(得分:3)

class AddressRegex {
    public static void main(String[] args) {

        String dbpath = "user1:password@192.168.1.3:3306/dbname1";       

        // I should point out my coworker is wrong when he says this is a
        // guy eating too big a sandwich!! It's just a set of delimiters!
        String[] tokens = dbpath.split(":|@|/");

        String user = tokens[0];
        String host = tokens[1];
        String port = tokens[2];
        String dbid = tokens[3];

        System.out.println(user);
        System.out.println(host);
        System.out.println(port);
        System.out.println(dbid);


    }

}

答案 2 :(得分:3)

这是解决您当前问题的方法。替代

\b

\\b

反斜杠需要在Java中进行转义。我试着这样做了:

"(\\b[A-Z0-9._%+-]+):([A-Z]+)@([A-Z0-9.-]+):([0-9]{1,5})/([A-Z0-9_-]+)"

您的代码已打印true

答案 3 :(得分:1)

String input = "user1:password@192.168.1.3:3306/dbname1";
Scanner scanner = new Scanner(input).useDelimiter("[:@/]");
String user = scanner.next();
String password = scanner.next();
String host = scanner.next();
int port = scanner.nextInt();
String dbName = scanner.next();