Reputation: 755
In my SQLite database I have a composite key that comprises of an email and a tutorial name (it's an e-learning app) such as [email protected] 1 or [email protected] 3. I'm having problem splitting the two when I use them later on. I want to get the tutorial (Tutorial 1) and email ([email protected]) separately. Seems straightforward but I'm struggling?
Here'se what I've tried so far:
String Key = cursor.getString(cursor.getColumnIndex("key"));
String email = Key.replace("^(.*)(Tutorial)(\\s)(\\d+)$", "$1");
String Tutorial = Key.replace("^(.*)(Tutorial)(\\s)(\\d+)$", "$2$3$4");
However when I use print statements later on, nothing is replaced or changed. Any ideas? Or is there a simpler way to do this?
Upvotes: 0
Views: 114
Reputation: 420951
You need to use replaceAll
(and not replace
) if you want to work with regexps. But in this case I'd recommend that you simply do:
int i = input.lastIndexOf("Tutorial");
String email = input.substring(0, i);
String tutorial = input.substring(i);
If you really want to go with regexps, I'd recommend something like
String key = "^(.*)(Tutorial \\d+)$";
String email = input.replaceAll(key, "$1");
String tutorial = input.replaceAll(key, "$2");
Upvotes: 1
Reputation: 174706
I think you want something like this,
System.out.println("[email protected] 1".replaceAll("^(.*?@[^A-Z]+)([A-Z]\\S+\\s*\\d+)$", "$1 $2"));
System.out.println("[email protected] 1".replaceAll("^(.*?@[^A-Z]+)([A-Z]\\S+\\s*\\d+)$", "$1"));
System.out.println("[email protected] 1".replaceAll("^(.*?@[^A-Z]+)([A-Z]\\S+\\s*\\d+)$", "$2"));
Output:
[email protected] Tutorial 1
[email protected]
Tutorial 1
Group 1 contains the email id and group 2 contains the string Tutorial
and following number.
Upvotes: 0
Reputation: 10208
If you want to go with regex, then something like this should work:
String pattern = "(.+)(Tutorial\\s\\d+)";
Pattern r = Pattern.compile(pattern);
String[] s = { "[email protected] 1",
"[email protected] 3" };
for (String str : s) {
Matcher m = r.matcher(str);
if (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
}
Upvotes: 0