I have a text and I'd like to write a regular expression to extract the string after second @
. For example: @ some text with letter, digit 123 1234 and symbols {[ @text_to_extract
. How would I write a regular expression to extract only the string after second @
. This code seems like a step in the right direction:
Pattern p = Pattern.compile("@@(.+?)");
Matcher m = p.matcher("asdasdas@@textToExtract");
This works when text between @
is empty, but how do I specify any text in a regex?
Pattern.compile("@(*)@(.+?)");
?
Edited:
One more condition, text can be between @
and @
but doesn't have to.
*
to .*
. Pattern.compile("@.*@(.+)");
The "non-greedy" operator should be removed. (.*?)
should be (.*)
... Otherwise you match just the minimum of the text after the second @. Definitely need a "." in front of the *. It means "0 or more of the proceeding character. Actually, maybe you want [^@]*
instead... so it matches anything but the at symbol.. so you're guaranteed to get everything, even if . doesn't match newlines. Anyway, here's working code.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
// Pattern p = Pattern.compile("@(*)@(.+?)");
Pattern p = Pattern.compile("@.*@(.+)");
Matcher m = p.matcher("asdasdas@@textToExtract");
while (m.find()) {
System.out.println(m.group(1));
}
}
}
Play with the code here: http://ideone.com/rxB5Zy
你应该这样
Matcher m =Pattern.compile("^[^@]*@[^@]*@([^@]*)").matcher(input);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.