天天看點

黑馬程式員 java學習筆記--正規表達式

---------------------- android教育訓練、 java教育訓練、期待與您交流! ----------------------

package cn.oyb.ce;
import java.util.regex.*;

public class Test2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Pattern pattern = Pattern.compile("\\d{4}\\-\\d+");
                String s = "0733-4706030";
		Matcher matcher = pattern.matcher(s);
		if (matcher.find())	//find()方法,就像你所想象的,用來搜尋與正規表達式相比對的任何目标字元串,
		{
			System.out.println(matcher.group());	//group()方法,用來傳回包含了所比對文本的字元串
			System.out.println(matcher.start());
		}
	}
}
           

(1)、Matcher方法

public int groupCount( )傳回matcher對象中的group的數目。不包括group0。

public String group( ) 傳回上次比對操作(比方說find( ))的group 0(整個比對)

public String group(int i)傳回上次比對操作的某個group。如果比對成功,但是沒能找到group,則傳回null。

public int start(int group)傳回上次比對所找到的,group的開始位置。

public int end(int group)傳回上次比對所找到的,group的結束位置,最後一個字元的下标加一。

(2)、split()  分割,

                String str = "asd.sds.sda.sssw";

String [] ss = str.split("\\.");

for(int i=0;i<ss.length;i++)

{

System.out.println(ss[i]);

}

(3)、replace(replaceAll) 替換

正規表達式在替換文本方面特别在行。下面就是一些方法:

replaceFirst(String replacement)将字元串裡,第一個與模式相比對的子串替換成replacement。

replaceAll(String replacement),将輸入字元串裡所有與模式相比對的子串全部替換成replacement。

appendReplacement(StringBuffer sbuf, String replacement)對sbuf進行逐次替換,而不是像replaceFirst( )或replaceAll( )那樣,隻替換第一個或全部子串。這是個非常重要的方法,因為它可以調用方法來生成replacement(replaceFirst( )和replaceAll( )隻允許用固定的字元串來充當replacement)。有了這個方法,你就可以程式設計區分group,進而實作更強大的替換功能。

String str = "asd.sds.sda.sssw";

String tostrF = str.replaceFirst("\\.", "@");

String tostr = str.replace("a", "M");

String tostrA = str.replaceAll("\\.", "@");

System.out.println(tostrF);

System.out.println(tostr);

System.out.println(tostrA);

----------------------------------------------------------------------

javascript中驗證使用者名不能以數字開頭和隻能是數字、字母、下劃線組成

// JS代碼

function onsub(){

var username = document.getElementById("username").value;

var pp = username.match("\\w+");

if(pp==null)

{

alert("使用者名必須是數字或字母下劃線組成!");

return false;

}

var pp2 = username.match("\\d");

if(pp2!=null)

{

alert("使用者名不能以數字開頭!");

return false;

}

}

//<form>表單

<form action="" method="post" οnsubmit="return onsub();">

使用者名:<input type="text" id="username" name="username" value="在這裡輸入">

</form>

---------------------- android教育訓練、 java教育訓練、期待與您交流! ----------------------