如何解决Java正则表达式中缺少的预处理操作?

时间:2013-09-12 11:17:27

标签: java regex sed

Java不支持regular expressions中的预处理操作。如何在Java中解决这个缺少的功能?

我想在Java中实现一个方法,它与这个GNU sed命令一样:

$ sed 's/\(^\|_\)\([a-z]\)/\U\2/g' <<< first_name
FirstName

sed调用产生驼峰。

3 个答案:

答案 0 :(得分:3)

为什么不简单地使用旧学校的字符串操作?

String myStr = "first_name";
myStr = myStr.replace("_", " ");
myStr = StrUtils.Capitalize(myStr);
myStr = mystr.replace(" ", "");

StrUtils来自http://commons.apache.org/lang/

如果您不想添加StrUtils,请拆分Words,并替换第一个字符,方法是将小写字母和大写字母之间的ASCII差异(我认为是32)添加到char中。 (或UpperCase功能等......)

答案 1 :(得分:1)

如果您尝试

public static void main(String[] args) {
    System.out.println(toTitleCase("first_name"));
    System.out.println(toTitleCase("UPPER_CASE"));
    System.out.println(toTitleCase("ßßß_ßßß_dždždž"));
}

public static String toTitleCase(String s) {
    StringBuilder sb = new StringBuilder();
    for (String word : s.split("_+")) {
        sb.append(word.substring(0,1).toUpperCase());
        sb.append(word.substring(1).toLowerCase());
    }
    return sb.toString();
}

打印

FirstName
UpperCase
SSßßSSßßDŽdždž

答案 2 :(得分:0)

我现在用这个:

class camelcase
{
  public static void capitalize (String str, StringBuilder builder)
  {
    int length = str.length();
    if (length > 0) {
      builder.append (Character.toTitleCase(str.charAt(0)));
      if (length > 1)
        builder.append (str.substring(1).toLowerCase());
    }
  }

  public static String capitalize (String str)
  {
    StringBuilder builder = new StringBuilder();
    capitalize (str, builder);
    return builder.toString();
  }

  public static void camelcase (String str, StringBuilder builder)
  {
    for (String word : str.split("[ \\p{Punct}]+"))
      capitalize (word, builder);
  }

  public static String camelcase (String str)
  {
    StringBuilder builder = new StringBuilder();
    camelcase (str, builder);
    return builder.toString();
  }

  public static void main (String[] args)
  {
    String[] strings = new String[] {
      "", "a", "aa", "aa_bb", "aa bb", "aa - bb", "ß", "ßß", "ßß_ßß", "dždž"
    };
    for (String str : strings)
      System.out.println ("'" + str + "' -> '" + camelcase (str) + "'");
  }
}