正则表达式java寻找特殊字符位置怎么操作
        
        
问题描述:正则表达式java寻找特殊字符位置怎么操作
推荐答案 本回答由问问达人推荐
在Java中,可以使用正则表达式来寻找特殊字符在字符串中的位置。下面是一种实现方法:
  import java.util.regex.*;
  public class Main {
  public static void main(String[] args) {
  String input = "Hello! How are you?";
  String pattern = "[!@#$%^&*()]";
  Pattern compiledPattern = Pattern.compile(pattern);
  Matcher matcher = compiledPattern.matcher(input);
  while (matcher.find()) {
  int startIndex = matcher.start();
  int endIndex = matcher.end();
  String matchedCharacter = input.substring(startIndex, endIndex);
  System.out.println("特殊字符: " + matchedCharacter);
  System.out.println("位置: " + startIndex + "-" + (endIndex - 1));
  }
  }
  }
在上述代码中,我们定义了一个输入字符串 input,其中包含一些特殊字符。然后,定义了一个匹配的模式 pattern,使用正则表达式 [!@#$%^&*()] 来匹配特殊字符。
接下来,通过 Pattern 类的 compile 方法将模式编译为一个 Pattern 对象,并通过 Matcher 类的 matcher 方法创建一个匹配器对象。然后,使用 while 循环和 matcher.find() 方法来寻找所有匹配的特殊字符。
在每次循环中,可以通过 matcher.start() 和 matcher.end() 方法获取匹配到的特殊字符的起始位置和结束位置。再通过 input.substring(startIndex, endIndex) 方法获取实际的特殊字符。
最后,将特殊字符和其位置打印出来,其中位置显示为起始位置和结束位置的范围。
这种方法可以用于寻找字符串中所有特殊字符的位置。
查看其它两个剩余回答
        
      
