判断字符串中特定字符
String name = request.getParameter( "name ");
name值可能为a“北京 天安门”或者b“北京 天安门”或者c“从天安门到地安门”
1、如何判断name的值中有空格如a
2、如果有多个空格,只保留一个空格如b。
3、如何判断name值中有“从...到...”
------解决方案--------------------楼主不好意思呀.上面那个有问题.哈.给你测了一下能达到你的要求.你试试吧.行就请结贴,
不行请马上提问
import java.util.regex.*;
import javax.swing.*;
public class RegexTest
{
public static void main(String[]args)
{
Pattern pattern =null;
String patternString = "[\\S]+[\\s]+[\\S]+|从[\\S]+到[\\S]+ ";
String str = "我爱 北京 ";
String str1 = "从兴县到太原 ";
pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);
if (matcher.matches())
{
Pattern pattern1 = null;
pattern1 = Pattern.compile( "[\\s]+ ");
Matcher matcher1 = pattern1.matcher(str);
String output = matcher1.replaceAll( " ");
System.out.println(output);
}
}
}
------解决方案--------------------问题一: Pattern p = Pattern.compile( "\\S*\\p{Blank}*\\S* ");
Matcher m = p.matcher( "a北京 天安门 ");
boolean flag = m.matches();
System.out.println(flag);
问题二;
Pattern p = Pattern.compile( "[ ]{1,} ");
Matcher m = p.matcher( "北京 天安 ");
while(m.find()){
System.out.println(m.replaceAll( " "));
}
问题三:
Pattern p = Pattern.compile( "从\\S*到\\S* ");
Matcher m = p.matcher( "从北京到天安 ");
while(m.find()){
System.out.println(m.group());
}