java 中的规则表达式

 

//This progame is to display how regex class work,
//how to find match subsequence from the Sting.
package com.src;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//\s	A whitespace character, short for [ \t\n\x0b\r\f]
//\S	A non-whitespace character, short for [^\s]
//\w	A word character, short for [a-zA-Z_0-9]
//\W	A non-word character [^\w]

public class RegexTest {
	 public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";
	public static void main(String[] args) {
		Pattern pattern = Pattern.compile("\\w+");
	    // in case you would like to ignore case sensitivity,
	    // you could use this statement:
	    // Pattern pattern = Pattern.compile("\\s+", Pattern.CASE_INSENSITIVE);
	    Matcher matcher = pattern.matcher(EXAMPLE_TEST);
	    System.out.println("xjf>>>"+matcher.groupCount());
	    //next subsequence of the input sequence that matches the pattern.
	    while (matcher.find()) {
	      System.out.print("Start index: " + matcher.start());
	      System.out.print(" End index: " + matcher.end() + " ");
	      //the expressions m.group() and s.substring(m.start(), m.end()) are equivalent. 
	      System.out.println(matcher.group());
	      System.out.println("EXAMPLE_TEST.substring>>>"+EXAMPLE_TEST.substring(matcher.start(), matcher.end()));
	    }
            
	    // now create a new pattern and matcher to replace whitespace with \n
	    Pattern replace = Pattern.compile("\\s+");
	    Matcher matcher2 = replace.matcher(EXAMPLE_TEST);
	    System.out.println(matcher2.replaceAll("\n"));
	}
}

 

the result is:

 

//the expressions m.group() and s.substring(m.start(), m.end())  are equivalent. 
//\w	A word character, short for [a-zA-Z_0-9]
Start index: 0 End index: 4 This
EXAMPLE_TEST.substring>>>This
Start index: 5 End index: 7 is
EXAMPLE_TEST.substring>>>is
Start index: 8 End index: 10 my
EXAMPLE_TEST.substring>>>my
Start index: 11 End index: 16 small
EXAMPLE_TEST.substring>>>small
Start index: 17 End index: 24 example
EXAMPLE_TEST.substring>>>example
Start index: 25 End index: 31 string
EXAMPLE_TEST.substring>>>string
Start index: 32 End index: 37 which
EXAMPLE_TEST.substring>>>which
Start index: 38 End index: 39 I
EXAMPLE_TEST.substring>>>I
Start index: 40 End index: 41 m
EXAMPLE_TEST.substring>>>m
Start index: 42 End index: 47 going
EXAMPLE_TEST.substring>>>going
Start index: 48 End index: 50 to
EXAMPLE_TEST.substring>>>to
Start index: 51 End index: 54 use
EXAMPLE_TEST.substring>>>use
Start index: 55 End index: 58 for
EXAMPLE_TEST.substring>>>for
Start index: 59 End index: 66 pattern
EXAMPLE_TEST.substring>>>pattern
Start index: 67 End index: 75 matching
EXAMPLE_TEST.substring>>>matching

//replace whitespace with \n 
This
is
my
small
example
string
which
I'm
going
to
use
for
pattern
matching.

 

 

 

 

 

你可能感兴趣的:(java)