---
title: "(转)Java中关于空格替换的正则表达式，实例代码"
author: "fonter"
date: "2011-04-10T20:32:16Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-04-10T20:32:16Z"
id: 996318
url: "https://fonter.iteye.com/blog/996318"
---

句点符号 . 是通配符 ,  * 零次或多次，+ 一次或多次，? 零次或一次，{n} 恰好n次，{n,m} 从n到m次  
要记住，老是拿\*当通配符，实际是 句号 . 是通配符

 

 

package [**test**]().function.excel;

public class RegTest {  
   
 public static void main(String\[] args) {  
     
  //Java中关于空格的正则表达式  
    
    
    String str2 = "GET             /index.html HTTP/1.1";  //字符串s由“GET”、“/index.html”和“HTTP/1.1”组成，中间有一个或多个空格  
    String tt\[] = str2.split("[\\\\s{1](),}");   //按照空格分割字符串，多个空格作为一个空格对字符串进行分割  
    for(String str: tt)//增强的for循环  
    System.out.println(str);//输出：GET  
                                       //  /index.html  
                                      //  HTTP/1.1           
     
    String qq = str2.replaceAll(" {2,}", " ");//把字符串s中的多个空格替换为一个空格  
    System.out.println(qq);//输出：GET /index.html HTTP/1.1  
    System.out.println(str2);//输出：GET             /index.html HTTP/1.1  
     
     
    // //split 按照空格分割字符串，多个空格作为一个空格对字符串进行分割  
    String strTest = "668947   18  109451074 0                0        33       700198   2335821 " ;  
    String resSplit\[] = strTest.split("[\\\\s{1](),}")  ;  
    for(int j =0 ;j&lt; resSplit.length;j++){  
     System.out.println(resSplit\[j]);  
    }  
     
     
    //句点符号 . 是通配符 ,  * 零次或多次，+ 一次或多次，? 零次或一次，{n} 恰好n次，{n,m} 从n到m次  
    String time = "dfda11:50:39" ;  
    if(time.matches(".\*\\\\d{2}:\\\\d{2}:\\\\d{2}")){  
     System.out.println("fu he");  
       }else{  
       System.out.println("bu fu he");  
       }  
     
    // 不使用句点  
    String time2 = "dfda11:50:39" ;  
    if(time2.matches("[\\\\d{2}:\\\\d{2}:\\\\d{2]()}")){  
     System.out.println("fu he");  
       }else{  
       System.out.println("bu fu he");  
       }  
   

 }  

}

 

转自：[http://www.51testing.com/?uid-202848-action-viewspace-itemid-226265](http://www.51testing.com/?uid-202848-action-viewspace-itemid-226265)