有一个字符串,比如"Abce&*)ghE349U",我想把里面的大写变成小写 ,小写变成大写,数字不变,其他变成*。如果用ascii码一个个判断我会,可是
我想用string的replaceAll方法,加上正则表达式实现,比如
String a = "Abce&*)ghE349U";
a.replaceAll("","")
请问这个正则表达式怎么写

解决方案 »

  1.   

    的确写52次replaceAll要创建52个对象,有点锉
      

  2.   

       我的理解是  这个好像不能用replaceAll来实现啊 因为不管你正则可以匹配 但是替换 永远是个字符串.你的描述是
    你替换后的东西也是不确定的 这就矛盾了....看来只有用你前面那方法了
        也许我是菜鸟 只供参考啊, 不过楼主也不要抱多大希望!
      

  3.   

    java JDK 不支持直接转换字符的大小写。
    不过,可以用下面的RegexHelper。
    import java.util.regex.*;
     
     
    /**
     * <p>RegexHelper provides alternative implementations of the Matcher
     * methods <tt>replaceAll</tt> and <tt>replaceFirst</tt>, with enhanced
     * processing of the replacement strings.  The major enhancement is that
     * cpaturing-group references can contain conversion specifiers that cause
     * the captured text to be processed in some way before being appended to 
     * the output string. Conversions can be specified by adding the appropriate
     * character between the dollar sign and the digit(s); valid conversions are:
     * </p><ul>
     *   <li> <tt>U</tt> : converts all characters in the group to uppercase.</li>
     *   <li> <tt>L</tt> : converts all characters in the group to lowercase.</li>
     *   <li> <tt>T</tt> : converts the first letter of each word to uppercase
     *     and all other letters to lowercase.</li>
     *   <li> <tt>t</tt> : converts the first letter in the group to uppercase
     *     and all other letters to lowercase.</li>
     * </ul>
     * <p>Conversions can only be performed on captured groups, and only one at
     * a time.  To perform a conversion on the entire match, use (for example)
     * <tt>$U0</tt>.</p>
     *
     * <p>Another enhancement is that the whitespace escapes "\t" and "\n", if
     * present in the replacement string, will be converted to TAB and LF,
     * respectively.  Unicode escapes of the form "\uXXXX" are also supported,
     * just as they are in the <tt>regex</tt> argument, which means any Unicode
     * character can be added to the output string.  Other than that, backslash
     * is used to indicate that the following character should not be treated
     * specially: "\$" becomes '$', and "\\" becomes '\'.  If you want to insert
     * the contents of group 1 followed by a zero, but your regex has ten or more
     * capturing groups, you would use "$1\0". If a backslash is the last character
     * in the replacement string, it will be appended to the output string.</p>
     *
     */
    public class RegexHelper
    {
      public static String replaceAll(String str, String regex, String repl)
      {
        Matcher m = Pattern.compile(regex).matcher(str);
     
        if (m.find())
        {
          StringBuffer sb = new StringBuffer();
        
          do {
            m.appendReplacement(sb, "");
            appendReplacement(sb, m, repl);
          } while (m.find());
      
          m.appendTail(sb);
          return sb.toString();
        }
        
        return str;
      }
     
     
      public static String replaceFirst(String str, String regex, String repl)
      {
        Matcher m = Pattern.compile(regex).matcher(str);
     
        if (m.find())
        {
          StringBuffer sb = new StringBuffer();
          m.appendReplacement(sb, "");
          appendReplacement(sb, m, repl);
          m.appendTail(sb);
          return sb.toString();
        }
        
        return str;
      }
     
     
      static void appendReplacement(StringBuffer sb, Matcher m, String repl)
      {
        int cursor = 0;
        int len = repl.length();
     
        while (cursor < len)
        {
          char nextChar = repl.charAt(cursor);
          if (nextChar == '\\' && cursor < len - 1)
          {
            nextChar = repl.charAt(++cursor);
            switch (nextChar)
            {
              case 't':
                sb.append('\t');
                break;
              case 'n':
                sb.append('\n');
                break;
              case 'u':
                char ch = unicodeValue(repl, cursor + 1);
                if (ch != '\u0000')
                {
                  cursor += 4;
                  sb.append(ch);
                }
                else
                {
                  sb.append('u');
                }
                break;
              default:
                sb.append(nextChar);
            }
            cursor++;
          }
          else if (nextChar == '$' && cursor < len - 1)
          {
            Conversion conversion = Conversion.NONE;
            char nextNextChar = repl.charAt(++cursor);
            if (nextNextChar < '0' || nextNextChar > '9')
            {
              if (cursor == len - 1)
              {
                sb.append('$').append(nextNextChar);
                cursor++;
                continue;
              }
              conversion = Conversion.valueOf(nextNextChar);
              if (conversion == Conversion.NONE)
              {
                sb.append('$');
                if (nextNextChar != '\\')
                {
                  sb.append(nextNextChar);
                  cursor++;
                }
                continue;
              }
              nextChar = repl.charAt(++cursor);
            }
            else
            {
              nextChar = nextNextChar;
            }
     
            int digit = Character.digit(nextChar, 10);
     
            if (digit == -1 || m.groupCount() < digit)
            {
              // It's not a (valid) group reference
              sb.append('$');
              if (conversion != Conversion.NONE)
              {
                sb.append(nextNextChar);
              }
              sb.append(nextChar);
              cursor++;
              continue;
            }
            int refNum = digit;
     
            // Capture the largest legal group string
            while (++cursor < len)
            {
              nextChar = repl.charAt(cursor);
              if ((digit = Character.digit(nextChar, 10)) == -1)
              {
                break;
              }
              int newRefNum = (refNum * 10) + digit;
              if (m.groupCount() < newRefNum)
              {
                break;
              }
              refNum = newRefNum;
            }
     
            // Append group if it matched anything
            String group = m.group(refNum);
            if (group != null && group.length() > 0)
            {
              sb.append(conversion.convert(group));
            }
          }
          else
          {
            sb.append(nextChar);
            cursor++;
          }
        }
      }
     
      private static char unicodeValue(String repl, int cursor)
      {
        int result = 0;
        int end = cursor + 4;
        if (end > repl.length())
        {
          return '\u0000';
        }
        for (int i = cursor; i < end; i++)
        {
          char next = repl.charAt(i);
          int n = Character.digit(next, 16);
          if (n == -1)
          {
            return '\u0000';
          }
          result = result * 16 + n;
        }
        return (char)result;
      }
     
      private static String titleize(String str, boolean allWords)
      {
        int strLen;
        if (str == null || (strLen = str.length()) == 0)
        {
          return str;
        }
        StringBuilder sb = new StringBuilder(strLen);
        boolean whitespace = true;
        for (int i = 0; i < strLen; i++)
        {
          char ch = str.charAt(i);
          if (Character.isWhitespace(ch))
          {
            sb.append(ch);
            whitespace = allWords;
          }
          else if (whitespace && Character.isLetter(ch))
          {
            sb.append(Character.toTitleCase(ch));
            whitespace = false;
          }
          else
          {
            sb.append(Character.toLowerCase(ch));
          }
        }
        return sb.toString();
      }
     
      private enum Conversion
      {
        NONE('\0')
        {
          public String convert(String str) { return str; } 
        },
        TO_UPPER_CASE('U')
        {
          public String convert(String str) { return str.toUpperCase(); } 
        },
        TO_LOWER_CASE('L')
        {
          public String convert(String str) { return str.toLowerCase(); } 
        },
        TO_TITLE_CASE('t')
        {
          public String convert(String str) { return RegexHelper.titleize(str, false); }
        },
        TITLE_CASE_ALL('T')
        {
          public String convert(String str) { return RegexHelper.titleize(str, true); }
        };
     
        public static Conversion valueOf(char ch)
        {
          for (Conversion conv : values())
          {
            if (conv.specifier == ch)
            {
              return conv;
            }
          }
          return NONE;
        }
     
        private final char specifier;
     
        private Conversion(char specifier)
        {
          this.specifier = specifier;
        }
     
        public abstract String convert(String str);
      }
      
      public static void main(String... args)
      {
        String s = "-aaa- -bbb-";
        System.out.println(RegexHelper.replaceAll(s, "-(.*?)-", "_$t1_"));
        System.out.println(RegexHelper.replaceFirst(s, "-(.*?)-", "_$U1_"));
      }
     
      private RegexHelper() {}
    }
      

  4.   

    String s2 = "Abce&*)ghE349U";

    s2=s2.replaceAll("[\\W]", "");

    System.out.println(s2);

    char [] c = s2.toCharArray();

    for(int i=0;i<c.length;i++){
    if(!(c[i]>=48 && c[i]<=57)){
    if(c[i]>97){
    c[i]= (char) (c[i]-32);
    }else{
    c[i]= (char) (c[i]+32);
    }
    }
    }

    System.out.println(new String(c));
      

  5.   

    使用RegexHelper解决lz问题,可以用以下代码:  public static void main(String... args)
      {
        String inString = "Abce&*)ghE349U";
        String outString = RegexHelper.replaceAll(inString, "([^A-Za-z0-9])", "\\*");
        System.out.println(outString);
        outString = RegexHelper.replaceAll(outString, "([a-z])", "$U1");
        System.out.println(outString);
        outString = RegexHelper.replaceAll(outString, "([A-Z])", "$L1");
        System.out.println(outString);
      }