Вы находитесь на странице: 1из 11

Problem Description:

How to reset the pattern of a regular expression?

Solution:
Following example demonstrates how to reset the pattern of a regular expression by using Pattern.compile() of Pattern class and m.find() method of Matcher class.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Resetting { public static void main(String[] args) throws Exception { Matcher m = Pattern.compile("[frb][aiu][gx]"). matcher("fix the rug with bags"); while (m.find()) System.out.println(m.group()); m.reset("fix the rig with rags"); while (m.find()) System.out.println(m.group()); } }

Result:
The above code sample will produce the following result.

fix rug bag fix rig rag

Problem Description:
How to match duplicate words in a regular expression?

Solution:
Following example shows how to search duplicate words in a regular expression by using p.matcher() method and m.group() method of regex.Matcher class.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main {

public static void main(String args[]) throws Exception { String duplicatePattern = "\\b(\\w+) \\1\\b"; Pattern p = Pattern.compile(duplicatePattern); int matches = 0; String phrase = " this is a test "; Matcher m = p.matcher(phrase); String val = null; while (m.find()) { val = ":" + m.group() + ":"; matches++; } if(val>0) System.out.println("The string has matched with the pattern."); else System.out.println("The string has not matched with the pattern."); } }

Result:
The above code sample will produce the following result.

The string has matched with the pattern.

Problem Description:
How to find every occurance of a word?

Solution:
Following example demonstrates how to find every occurance of a word with the help of Pattern.compile() method and m.group() method.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) throws Exception { String candidate = "this is a test, A TEST."; String regex = "\\ba\\w*\\b"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(candidate); String val = null; System.out.println("INPUT: " + candidate); System.out.println("REGEX: " + regex + "\r\n"); while (m.find()) { val = m.group();

System.out.println("MATCH: " + val); } if (val == null) { System.out.println("NO MATCHES: "); } } }

Result:
The above code sample will produce the following result.

INPUT: REGEX: MATCH: MATCH:

this is a test ,A TEST. \\ba\\w*\\b a test A TEST

Problem Description:
How to know the last index of a perticular word in a string?

Solution:
Following example demonstrates how to know the last index of a perticular word in a string by using Patter.compile() method of Pattern class and matchet.find() method of Matcher class.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) { String candidateString = "This is a Java example. This is another Java example."; Pattern p = Pattern.compile("Java"); Matcher matcher = p.matcher(candidateString); matcher.find(); int nextIndex = matcher.end(); System.out.print("The last index of Java is:"); System.out.println(nextIndex); } }

Result:
The above code sample will produce the following result.

The last index of Java is: 42

Problem Description:
How to print all the strings that match a given pattern from a file?

Solution:
Following example shows how to print all the strings that match a given pattern from a file with the help of Patternname.matcher() method of Util.regex class.

import java.util.regex.*; import java.io.*; public class ReaderIter { public static void main(String[] args) throws IOException { Pattern patt = Pattern.compile("[A-Za-z][a-z]+"); BufferedReader r = new BufferedReader (new FileReader("ReaderIter.java")); String line; while ((line = r.readLine()) != null) { Matcher m = patt.matcher(line); while (m.find()) { System.out.println(m.group(0)); int start = m.start(0); int end = m.end(0); Use CharacterIterator.substring(offset, end); System.out.println(line.substring(start, end)); } } } }

Result:
The above code sample will produce the following result.

Ian Darwin http www darwinsys com All rights reserved Software written by Ian Darwin and others

Problem Description:
How to remove the white spaces?

Solution:
Following example demonstrates how to remove the matcher.replaceAll(stringname) method of Util.regex.Pattern class. white spaces with the help

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] argv) throws Exception { String ExString = "This is a Java program. This is another Java Program."; String result=removeDuplicateWhitespace(ExString); System.out.println(result); } public static CharSequence removeDuplicateWhitespace(CharSequence inputStr) { String patternStr = "\\s+"; String replaceStr = " "; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(inputStr); return matcher.replaceAll(replaceStr); } }

Result:
The above code sample will produce the following result.

ThisisaJavaprogram.ThisisanotherJavaprogram.

Problem Description:
How to match phone numbers in a list?

Solution:
Following example shows how to match phone numbers in a list to a perticlar pattern by using phone.matches(phoneNumberPattern) method .

public class MatchPhoneNumber { public static void main(String args[]) { isPhoneValid("1-999-585-4009"); isPhoneValid("999-585-4009");

isPhoneValid("1-585-4009"); isPhoneValid("585-4009"); isPhoneValid("1.999-585-4009"); isPhoneValid("999 585-4009"); isPhoneValid("1 585 4009"); isPhoneValid("111-Java2s"); } public static boolean isPhoneValid(String phone) { boolean retval = false; String phoneNumberPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}"; retval = phone.matches(phoneNumberPattern); String msg = "NO MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern; if (retval) { msg = " MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern; } System.out.println(msg + "\r\n"); return retval; } }

Result:
The above code sample will produce the following result.

MATCH: pattern:1-999-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} MATCH: pattern:999-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} MATCH: pattern:1-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:1.999-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:999 585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:1 585 4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:111-Java2s regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

Problem Description:
How to count a group of words in a string?

Solution:
Following example demonstrates how to count a group of words in a string with the help of matcher.groupCount() method of regex.Matcher class.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherGroupCountExample { public static void main(String args[]) { Pattern p = Pattern.compile("J(ava)"); String candidateString = "This is Java. This is a Java example."; Matcher matcher = p.matcher(candidateString); int numberOfGroups = matcher.groupCount(); System.out.println("numberOfGroups =" + numberOfGroups); } }

Result:
The above code sample will produce the following result.

numberOfGroups =3

Problem Description:
How to search a perticular word in a string?

Solution:
Following example demonstrates how to search a perticular word in a string with the help of matcher.start() method of regex.Matcher class.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) { Pattern p = Pattern.compile("j(ava)"); String candidateString = "This is a java program. This is another java program."; Matcher matcher = p.matcher(candidateString); int nextIndex = matcher.start(1); System.out.println(candidateString); System.out.println("The index for java is:" + nextIndex); } }

Result:
The above code sample will produce the following result.

This is a java program. This is another java program.

The index for java is: 11

Problem Description:
How to split a regular expression?

Solution:
Following example demonstrates how to split a regular expression by using Pattern.compile() method and patternname.split() method of regex.Pattern class.

import java.util.regex.Pattern; public class PatternSplitExample { public static void main(String args[]) { Pattern p = Pattern.compile(" "); String tmp = "this is the Java example"; String[] tokens = p.split(tmp); for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } } }

Result:
The above code sample will produce the following result.

this is the Java example

Problem Description:
How to count replace first occourance of a String?

Solution:
Following example demonstrates how to replace first occourance of a String in a String using replaceFirst() method of a Matcher class.

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

public class Main { public static void main(String args[]) { Pattern p = Pattern.compile("hello"); String instring = "hello hello hello."; System.out.println("initial String: "+ instring); Matcher m = p.matcher(instring); String tmp = m.replaceFirst("Java"); System.out.println("String after replacing 1st Match: " +tmp); } }

Result:
The above code sample will produce the following result.

initial String: hello hello hello. String after replacing 1st Match: Java hello hello.

Problem Description:
How to check check whether date is in proper format or not?

Solution:
Following example demonstrates how to check whether the date is in a proper format or not using matches method of String class.

public class Main { public static void main(String[] argv) { boolean isDate = false; String date1 = "8-05-1988"; String date2 = "08/04/1987" ; String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}"; isDate = date1.matches(datePattern); System.out.println("Date :"+ date1+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate); isDate = date2.matches(datePattern); System.out.println("Date :"+ date2+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate); } }

Result:
The above code sample will produce the following result.

Date :8-05-1988: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:true

Date :08/04/1987: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:false

Problem Description:
How to validate an email address format?

Solution:
Following example demonstrates how to validate e-mail address using matches() method of String class.

public class Main { public static void main(String[] args) { String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\ @([\\w]+\\.)+[\\w]+[\\w]$"; String email1 = "user@domain.com"; Boolean b = email1.matches(EMAIL_REGEX); System.out.println("is e-mail: "+email1+" :Valid = " + b); String email2 = "user^domain.co.in"; b = email2.matches(EMAIL_REGEX); System.out.println("is e-mail: "+email2 +" :Valid = " + b); } }

Result:
The above code sample will produce the following result.

is e-mail: user@domain.com :Valid = true is e-mail: user^domain.co.in :Valid = false

Problem Description:
How to replace all occurings of a string?

Solution:
Following example demonstrates how to replace all occouranc of a String in a String using replaceAll() method of Matcher class.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) { Pattern p = Pattern.compile("hello"); String instring = "hello hello hello."; System.out.println("initial String: "+ instring);

Matcher m = p.matcher(instring); String tmp = m.replaceAll("Java"); System.out.println("String after replacing 1st Match: " +tmp); } }

Result:
The above code sample will produce the following result.

initial String: hello hello hello. String after replacing 1st Match: Java Java Java.

Problem Description:
How to make first character of each word in Uppercase?

Solution:
Following example demonstrates how to convert first letter of each word in a string into an uppercase letter Using toUpperCase(), appendTail() methods.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String str = "this is a java test"; System.out.println(str); StringBuffer stringbf = new StringBuffer(); Matcher m = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(str); while (m.find()) { m.appendReplacement(stringbf, m.group(1).toUpperCase() + m.group(2).toLowerCase()); } System.out.println(m.appendTail(stringbf).toString()); } }

Result:
The above code sample will produce the following result.

this is a java test This Is A Java Test

Вам также может понравиться