我们如何使用正则表达式限制生成的文件名只需要20个字符?

时间:2016-01-07 07:14:34

标签: java regex

您好我尝试使用此正则表达式

^(?=[^,]+,[^,]+$)[a-zA-Z,]{1,20}$

但它没有用。

有没有办法实现这个目标?

意思是说,在从文件写入中保存文件时,文件名应该小于或等于20个字符长,20之后的字符应该被修剪。

2 个答案:

答案 0 :(得分:1)

你不需要regexp用于修剪字符串:

 awk '{
  tmp="echo " $2 " | openssl md5 | cut -f2 -d\" \""
  tmp | getline cksum
   $2=cksum
  print
  }' < sample

答案 1 :(得分:0)

您只能使用正则表达式执行检查,并在正则表达式中进行少量增强(请参阅stribizhev注释)。

private static final Matcher FILENAME_CHECKER = Pattern.compile("^(?=[^,]+,[^,]+$)([a-zA-Z,]{1,20})[a-zA-Z,]*$").matcher("");

/**
 * 
 * ...filename requirements go here...
 * 
 * @param unsanitizedFilename the filename to sanitize
 * @return a sanitized filename
 * 
 * @throws IllegalArgumentException If the filename doesn't honor all requirements. 
 */
public static String sanitizeFilename(String unsanitizedFilename) {
    FILENAME_CHECKER.reset(unsanitizedFilename);
    if (FILENAME_CHECKER.find() == false) {
        throw new IllegalArgumentException("Invalid filename: " + unsanitizedFilename);
    }

    return FILENAME_CHECKER.group(1);
}

Java 7 +

如果您使用的是Java 7+,则可以使用以下版本并利用命名组。

private static final Matcher FILENAME_CHECKER = Pattern.compile("^(?=[^,]+,[^,]+$)(?<valid_portion>[a-zA-Z,]{1,20})[a-zA-Z,]*$").matcher("");

public static String sanitizeFilename(String unsanitizedFilename) {
    FILENAME_CHECKER.reset(unsanitizedFilename);
    if (FILENAME_CHECKER.find() == false) {
        throw new IllegalArgumentException("Invalid filename: " + unsanitizedFilename);
    }

    return FILENAME_CHECKER.group("valid_portion");
}

线程安全

Matcher calss不是线程安全的。如果在您的情况下担心线程安全,那么这里是依赖于Pattern类的线程安全版本。

private static final Pattern FILENAME_CHECKER = Pattern.compile("^(?=[^,]+,[^,]+$)([a-zA-Z,]{1,20})[a-zA-Z,]*$");

/**
 * 
 * ...filename requirements go here...
 * 
 * @param unsanitizedFilename the filename to sanitize
 * @return a sanitized filename
 * 
 * @throws IllegalArgumentException If the filename doesn't honor all requirements. 
 */
public static String sanitizeFilename(String unsanitizedFilename) {
    Matcher m = FILENAME_CHECKER.matcher(unsanitizedFilename);
    if (m.find() == false) {
        throw new IllegalArgumentException("Invalid filename: " + unsanitizedFilename);
    }

    return m.group(1);
}