黑马程序员技术交流社区

标题: 正则表达式的问题 [打印本页]

作者: 何小红    时间: 2012-9-21 22:15
标题: 正则表达式的问题
java正则表达式检测字符串中第一个字母或数字出现位置的下标
要得到字符串:“你好,空指针,Welcome to 游戏大厅! ”  中“W” 出现位置的下标(index 应该是:7) ,用正则表达式怎么办??
作者: 程振    时间: 2012-9-21 23:08
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;


  3. public class RegexDemo {
  4.         public static void main(String[] args) {
  5.                 Pattern pattern = null;
  6.                 Matcher matcher = null;
  7.                
  8.                 pattern = Pattern.compile("W");
  9.                 matcher = pattern.matcher("你好,空指针,Welcome to 游戏大厅!");
  10.                 while(matcher.find()){
  11.                         System.out.println(matcher.start());
  12.                 }
  13.         }
  14. }
复制代码

作者: 汪小照    时间: 2012-9-22 00:01
import java.util.regex.*;
class Reg
{
public static void main(String [] args)
{
  String str = "你好,空指针,Welcome to 游戏大厅!";
  String reg = "W";
  //将正则表达式封装成对象
  Pattern p = Pattern.compile(reg);
  //让正则对象和要作用的字符串相关联,获取匹配对象
  Matcher m = p.matcher(str);
  //对字符串进行查找
  while(m.find())
  {
   System.out.println("要查找的结果在字符串中出现的位置index="+
    m.start());
  }
}
}

12.jpg (6.41 KB, 下载次数: 105)

打印结果

打印结果





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2