I am looking for a pattern to match this "LA5@10.232.140.133@Po6"
and one more "LA5@10.232.140.133@Port-channel7"
expression in Java using regular expression.
Like we have \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3} for IP address validation.
Can we have the pattern like below? Please suggest--
[a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9]@\d{1,3}\.\d{1,3}\.\d{1,3}\.\d开发者_运维知识库{1,3}@Po\d[1-9]
[a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9]@\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}@Port-channel\d[1-9]
Thanks in advance.
==============================
In my program i have,
import java.util.regex.*;
class ptternmatch {
public static void main(String [] args) {
Pattern p = Pattern.compile("\\w\\w\\w@\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}@*");
Matcher m = p.matcher("LA5@10.232.140.133@Port-channel7");
boolean b = false;
System.out.println("Pattern is " + m.pattern());
while(b = m.find()) {
System.out.println(m.start() + " " + m.group());
}
}
}
But i am getting compilation error with the pattern.--> Invalid escape sequence The sequence will be like a ->a 3 character word of digit n letter@ipaddress@some text..
Well, if you want to validate the IP address, then you need something a little bit more involved than \d{1,3}
. Also, keep in mind that for Java string literals, you need to escape the \
with \\
so you end up with a single backslash in the actual regex to escape a character such as a period (.
).
Assuming the LA5@
bit is static and that you're fine with either Po
or Port-channel
followed by a digit on the end, then you probably need a regex along these lines:
LA5@(((2((5[0-5])|([0-4][0-9])))|(1[0-9]{2})|([1-9][0-9]?)\\.){3}(2(5[0-5]|[0-4][0-9]))|(1[0-9]{2})|([1-9][0-9]?)@Po(rt-channel)?[1-9]
(Bracketing may be wonky, my apologies)
You can do something like matcher.find()
and, if it is true, the groups to capture the information. Take a look a the tutorial here:
- http://download.oracle.com/javase/tutorial/essential/regex/
You would need to wrap the necessary parts int parentheses - e.g. (\d{1,3})
. If you wrap all 4, you will have 4 groups to access.
Also, take a look at this tutorial
- http://www.javaworld.com/javaworld/jw-07-2001/jw-0713-regex.html?page=3
It's a very good tutorial, I think this one would explain most of your questions.
To match the second of your strings:
- LA5@10.232.140.133@Port-channel7
you can use something like:
\w{2}\d@\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}@[a-zA-Z\-]+\d
This depends on what you want to do, so the regex might change.
精彩评论