Top Java Regular Expression(Regex)frequently asked interview questions.
Q: What are Java Regex ?
A:Java provides the java.util.regex package for pattern matching with regular expressions.
It is widely used to define the constraint on strings such as password and email validation.
The java.util.regex package provides following classes and interfaces for regular expressions.
- MatchResult interface
- Matcher class
- Pattern class
- PatternSyntaxException class
A:
String lines[] = string.split("\\r?\\n");
Q: What is use of Dot(.) symbol in Java Regex?
A: The dot is used for matching any character. For example, the following regex represents "a number plus any other character":
[0-9].
Q: How to extract a substring using regex ?
Example - String test = "This is a test String and 'This is data we want'"
A:
String data = "This is a test String and 'This is data we want'"; Pattern pattern = Pattern.compile("'(.*?)'"); Matcher matcher = pattern.matcher(data); if (matcher.find()) { System.out.println(matcher.group(1)); }