JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Program: How to capture or extract a value(s) from text using regular expression in java?


Description:

The below example shows how to extract a specific pattern from a large text. The example tries to capture any IP addresses in the given text.


Code:
package com.java2novice.regex;

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

public class MyGroupRegex {

	private static Pattern ptn = 
			Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
	
	public static List<String> captureValues(String largeText){
		Matcher mtch = ptn.matcher(largeText);
		List<String> ips = new ArrayList<String>();
		while(mtch.find()){
			ips.add(mtch.group());
		}
		return ips;
	}
	
	public static void main(String a[]){
		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";
		System.out.println(captureValues(str));
	}
}

Output:
[10.20.30.40, 23.12.56.34, 3.90.23.65]
<< Previous Program | Next Program >>

List Of Regular Expression Sample Programs:

  1. Simple regex pattern matching using string matches().
  2. Simple java regex using Pattern and Matcher classes.
  3. Java regex with case insensitive.
  4. How to validate IP address using regular expression?
  5. How to replace a pattern using regular expression in java?
  6. How to remove multiple spaces with a single space with in a string?
  7. How to validate user name using regular expression?
  8. How to validate email address using regular expression?
  9. How to validate password using regular expression?
  10. How to validate file extensions using regular expression in java?
  11. How to validate date format using regular expression in java?
  12. How to capture or extract a value(s) from text using regular expression in java?
  13. How to split a string using regular expression?
Knowledge Centre
What is daemon thread?
Daemon thread is a low priority thread. It runs intermittently in the back ground, and takes care of the garbage collection operation for the java runtime system. By calling setDaemon() method is used to create a daemon thread.
Famous Quotations
I respect faith, but doubt is what gets you an education.
-- Wilson Mizner

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2018 by Nataraja Gootooru. All Rights Reserved.