I have a string "any tag$@ws2-role$@ws1-role" and I want to have a regular expression to search a word starting with "$@" and ending either with "$@" or with end of a line.
For example, for the above input, the output has to be ws2-role and ws1-role.
I tried below regular expression but I am not able to figure out how to add or operator for pattern2 so that it can also consider end of line for giving the output eg $@|$. $@ is the exact word to be match and $ to look until the end of line.
String pattern1 = "$@";
String pattern2 = "$@";
Pattern pattern = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher matcher = pattern.matcher(tag);
// check all occurance
while (matcher.find()) {
System.out.println(matcher.group());
}
Can anyone gives some hints?
Many Thanks in Advance
Try this
Pattern pattern = Pattern.compile("\\$@([^\\$@]+|$)");
CharSequence tag = "any tag$@ws2-role$@ws1-role";
Matcher matcher = pattern.matcher(tag);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
ws2-role
ws1-role
您可以为此使用基于前瞻的正则表达式:
String regex = "\\$@\\S+(?=\\$@|$)";
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.