0

I am trying to write a Regex pattern to find java collections declarations. Example: i want to match below lines

private List<String> test;
private HashMap<String, HashMap<String, String>> test1;

I am trying the Pattern

(private|public|protected) [A-Za-z]{1,}<([A-Za-z]* *\W*[A-Za-z]\W*)> *[A-za-z]*;
Hulk
  • 6,399
  • 1
  • 30
  • 52
  • 2
    You can't parse Java with a regex, and no parser can identify whether `List` refers to `java.util.List` or something else. – chrylis -cautiouslyoptimistic- Oct 05 '20 at 05:55
  • Closely related question: https://stackoverflow.com/questions/6751105/why-its-not-possible-to-use-regex-to-parse-html-xml-a-formal-explanation-in-la – Hulk Oct 05 '20 at 06:04
  • 1, If you are going to parse/validate _arbitrary infinite_ nested structures in collection declaration, [this is not possible using regular expressions](https://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns). It may work _only_ with the fixed number of nested levels. 2. Please review the pattern of Java identifier -- it would fail even for your example because it does not include digits as well other valid characters. – Nowhere Man Oct 05 '20 at 06:05
  • Also, this will not only match declarations of collections, but all object declarations of generic types. And it will miss collections declared as rawtypes. – Hulk Oct 05 '20 at 06:15
  • What something as simple as `List|ArrayList|LinkedList|Set|TreeSet|HashSet|Map|TreeMap|HashMap` suffice? – Kevin Anderson Oct 05 '20 at 06:20

0 Answers0