用于检测大小写和类型更改并进行转换的Java regex

g52tjvyc  于 2023-01-01  发布在  Java
关注(0)|答案(2)|浏览(70)

Java 11中,我尝试使用正则表达式来构建一个方法,该方法接受String,转换它,并返回转换后的结果。
具体来说,字符串必须只包含1+个字母数字字符([a-zA-Z0-9]+),每当两个连续的字符/元素改变大小写或从字母-〉数字切换(反之亦然)时,我希望在它们之间插入一个连字符("-")。
因此:

INPUT             RESULT
====================================
flimFlam          flim-Flam
fliMflam          fliM-flam
fliM8fLam         fli-M-8-f-Lam
flim$Flam         Illegal! $ not allowed!

目前为止我最好的尝试是:

public String hyphenate(String input) {

    // validate
    String regex = "[a-zA-Z0-9]+";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    if (!matcher.matches()) {
        throw new IllegalArgumentException("Illegal!");
    }

    // TODO: how to efficiently iterate down the 'input' string and insert hyphen
    // whenever case changes or 2 consecutive elements switch from alpha -> numeric
    // or numeric -> alpha ?

}
    • 关于如何高效地完成此 * 连字符 ,您有什么想法吗?*
6rqinv9w

6rqinv9w1#

使用正则表达式可以尝试:

String input = "fliM8fLam";
String output = input.replaceAll("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)|(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[a-z])", "-");
System.out.println(output);  // fli-M-8-f-L-am
xienkqul

xienkqul2#

1.您可以使用[^\\p{Alnum}]检查非字母数字字符。了解有关documentation模式的更多信息。
1.您可以使用[a-z]+(?=[A-Z\d])|[A-Z]+[a-z]+|\d+|[A-Z]获取匹配组。从this demo了解有关此模式的更多信息。您可以使用常规循环或Stream API连接匹配组,如以下演示所示。

    • 演示**:
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

class Main {
    public static void main(String[] args) {
        // Test
        String[] arr = {
                "flimFlam",
                "fliMflam",
                "fliM8fLam",
                "flim$Flam"
        };
        for (String s : arr) {
            try {
                System.out.println("Trying to hyphenate " + s);
                System.out.println(hyphenate(s));
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static String hyphenate(String input) {
        if (Pattern.compile("[^\\p{Alnum}]").matcher(input).find()) {
            throw new IllegalArgumentException("Illegal!");
        }

        String regex = "[a-z]+(?=[A-Z\\d])|[A-Z]+[a-z]+|\\d+|[A-Z]";
        return Pattern.compile(regex)
                .matcher(input)
                .results()
                .map(MatchResult::group)
                .collect(Collectors.joining("-"));
    }
}
    • 输出**:
Trying to hyphenate flimFlam
flim-Flam
Trying to hyphenate fliMflam
fli-Mflam
Trying to hyphenate fliM8fLam
fli-M-8-f-Lam
Trying to hyphenate flim$Flam
Illegal!

相关问题