PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

One

Find one match.
 
package testexample;
import java.util.regex.*;

public class Testexample {
    
    public static void main(String[] args) {
        
        String text = "my 1st string";
        String regex = "\d+\w+";
        
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);
        
        if(m.find()) {
            
            String match = m.group();
            System.out.println("match [" + match + "]");
        } 
        // matched [1st]
    }
    
}
... 10 lines
 
All    (2/3)

All

Find all matches
 
package testexample;

import java.util.regex.*;

public class Testexample {
    
    public static void main(String[] args) {
        
        String text = "Mastering Regular Expressions";        
        Matcher m = Pattern.compile("\w+").matcher(text);
        
        while(m.find()) {
            System.out.println("match [" + m.group() + "]");
        } 
        
        // match [Mastering]
        // match [Regular]
        // match [Expressions]
    }
}
... 9 lines
 
Url    (3/3)

Url

Identify and report on the URL's protocol, hostname and optional port number.
 
package testexample;
import java.util.regex.*;
public class Testexample {
    
    public static void main(String[] args) {
        
        String url = "http://www.minte9.com:8080/regex & not/an/url";
        String regex = "(?x) (https?):// ([^/:]+) :? ([0-9]+)?";
        
        Matcher m = Pattern.compile(regex).matcher(url);
        
        if (m.find()) {
            System.out.println(""
                    + "Overall [" + m.group() + "] (from " + m.start() + " to " + m.end() + ") \n" 
                    + "Protocol [" + m.group(1) + "] (from " + m.start(1) + " to " + m.end(1) + ") \n" 
                    + "Hostname [" + m.group(2) + "] (from " + m.start(2) + " to " + m.end(2) + ")"
           );
            
           if (m.group(3) != null) {
                System.out.println(""
                    + "Port [" + m.group(3) + "] "
                    + "  (from " + m.start(3) + " to " + m.end(3) + ") \n"
                );
           } else {
               System.out.println("No port; default 80 is assumed");
           }
        }
    }

}
... 19 lines
 

Questions    
Search

        A B C D E F
🔔
1/3