How to Extract a Value From Text in Java


In this example we will show how to capture or extract a value from text using regular expression in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CaptureValue {

	public static void main(String[] args) {
		
		String str = "Hi my machine IP is 10.20.30.40 and i would like "+
	            "to access port 80 from the host 23.12.56.34, which internally"+
	            "connects to 3.90.23.65. Please process the request";
		Pattern pattern = Pattern.compile("(d{1,3}).(d{1,3}).(d{1,3}).(d{1,3})");
		Matcher matcher = pattern.matcher(str);
		List ips = new ArrayList();
		while(matcher.find()){
            ips.add(matcher.group());
        }
		System.out.println(ips);
	}

}

Output:

[10.20.30.40, 23.12.56.34, 3.90.23.65]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments