java extract address items by regex
I have a string: user1:password@192.168.1.3:3306/dbname1 and I need to fill the username, password, host, port and dbname variables... my code:
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 matc开发者_运维技巧her = p.matcher(dbpath);
System.out.println(matcher.matches());
Output:
false
:( show me my mistake please... Thank you.
Here's a much simpler version that's not 100% correct, but it does the Job in your case:
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
Here's the fix to your immediate problem. Substitute
\b
with
\\b
Backslashes need to be escaped in Java. I tried it with this:
"(\\b[A-Z0-9._%+-]+):([A-Z]+)@([A-Z0-9.-]+):([0-9]{1,5})/([A-Z0-9_-]+)"
And your code printed true
.
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);
}
}
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();
精彩评论