[Q#4915967][A#4916023] How Match a Pattern in Text using Scanner and Pattern Classes?
https://stackoverflow.com/q/4915967
i want to find whether a particular pattern exists in my text file or not. i m using following classes for this : my sample text Line is and, i want to match following kind of pattern : where, at A's position a-z or A-Z but single charter. at 102's position any integer and of any length. at 190's position any integer and of any length. and,My code for pattern matching is: but, pattern is not matching even it exist there.. i think the problem is with my pattern string : anybody, Plz help me what pattern string should i use????
Answer
https://stackoverflow.com/a/4916023
I'm not sure that Scanner is the best tool for this as hasNext(Pattern) checks to see if the next complete token has the next pattern. Your pattern goes across tokens. Have you tried using a Matcher object instead of the Scanner?
APIzation
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Foo2 {
public static void main(String[] args) {
String line = "DBREF 1A1F A 102 190 UNP P08046 EGR1_MOUSE 308 396";
Pattern p = Pattern.compile("\\s+[a-zA-Z]\\s+\\d{1,}\\s+\\d{1,}\\s+");
Matcher matcher = p.matcher(line);
while (matcher.find()) {
System.out.printf("group: %s%n", matcher.group());
}
System.out.println("done");
}
}
package com.stackoverflow.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Human4916023 {
public static void MatchPattern(String line, String patternElements) {
Pattern p = Pattern.compile(patternElements);
Matcher matcher = p.matcher(line);
while (matcher.find()) {
System.out.printf("group: %s%n", matcher.group());
}
System.out.println("done");
}
}
package com.stackoverflow.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* How Match a Pattern in Text using Scanner and Pattern Classes?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/4916023">https://stackoverflow.com/a/4916023</a>
*/
public class APIzator4916023 {
public static void match(String line) {
Pattern p = Pattern.compile("\\s+[a-zA-Z]\\s+\\d{1,}\\s+\\d{1,}\\s+");
Matcher matcher = p.matcher(line);
while (matcher.find()) {
System.out.printf("group: %s%n", matcher.group());
}
System.out.println("done");
}
}