working with regular expressions in Java

regex matching in Java

Search for: regex matching in Java

Here is a java regex tutorial

Here is a comprehensive site on regex including java

Search for: java.util.regex package

regex cheetsheet

online regex tester

Somework in powershell I did in regex

Use of . dot in regex

Search for: Use of . dot in regex

Behavior of [] called a character class is explained here

(.*) inside a group in regex

Search for: (.*) inside a group in regex

Brackets are explained here

See this medium article


Filename: SomeString_2020-03-26_12-50-00.csv

([a-zA-Z0-9]+)_(\\d{4}-\\d\\d-\\d\\d)_(\\d\\d-\\d\\d-\\d\\d)\\.(.*)

Breaking it down

Any name that has alphanumeric one or more
([a-zA-Z0-9]+)

Separator _
_

Digits
(\\d{4}-\\d\\d-\\d\\d)
_


Digits
(\\d\\d-\\d\\d-\\d\\d)

Literal escaped "."
\\.

Any thing in extension
(.*)

Forecaster_plant_HA_2020-02-22_10-00-00.csv

^[a-zA-Z0-9]+_[a-zA-Z0-9]+_HA_\d\d\d\d-\d\d-\d\d_\d\d-\d\d-\d\d.csv$

* Zero or more
+ one or more
? one or none
. any character

[.x]+ means "." or "x" one or more time
you don't have to do 

[\.x\ to escape the "."

2030 I am still finding it hard to find a decent reference for REGEX!!!!!


public static List<String> splitString(String s, String regexPattern)
      {
         Pattern p = Pattern.compile(regexPattern);
         Matcher m = p.matcher(s);
         if (m.find() == false)
         {
            return null;
         }
         int count = m.groupCount();
         // index 0 is the whole match. So ignore it
         List<String> parts = new ArrayList<String>();
         for(int i=1; i<= count;i++)
         {
            parts.add(m.group(i));
         }
         return parts;
      }

private static void test2()
   {
      String s = "SomeString_2020-03-26_12-50-00.csv";
      String regex = "([a-zA-Z0-9]+)_(\\d{4}-\\d\\d-\\d\\d)_(\\d\\d-\\d\\d-\\d\\d)\\.(.*)";
      
      List<String> fields = splitString(s, regex);
      putils.p(fields.toString());
   }

[SomeString, 2020-03-26, 12-50-00, csv]

Some basic features

A more comprehensive reference for characters