簡體   English   中英

REGEX 用字符串替換數字

[英]REGEX to replace numbers with String

我有一個字符串如下:

((((1 OR 2) AND 3) OR 11) AND 23)

我想用字符串值替換數字。

我是正則表達式的新手,無法弄清楚如何替換范圍內的數字。

這是我的代碼來解決您的問題。 我可憐的正則表達式知識不足以僅使用正則表達式來解決。

public static void main(String[] args)
{
    String temp = "(X)+|";
    String regex = "";
    String text = "((((1 OR 2) AND 3) OR 11) AND 23)";
    Map<String, String> numberToString = new TreeMap<>((o1, o2) -> Integer.valueOf(o2) - Integer.valueOf(o1));

    numberToString.put("3", "THREE");
    numberToString.put("2", "TWO");
    numberToString.put("1", "ONE");
    numberToString.put("11", "ELEVEN");
    numberToString.put("23", "TWENTYTHREE");

    for(String number : numberToString.keySet()){
        regex = regex + temp.replace("X", number);
    }
    regex = regex.substring(0, regex.lastIndexOf('|'));
    Set<String> allMatches = new TreeSet<>((o1, o2) -> Integer.valueOf(o2) - Integer.valueOf(o1));
    Matcher m = Pattern.compile(regex).matcher(text);
    while (m.find()) {
        allMatches.add(m.group());
    }
    for (String match : allMatches) {
        if (numberToString.get(match) != null)
            text = text.replaceAll(match, numberToString.get(match));
    }

    System.out.println(text);
    System.out.println(regex);
}

使用 str.replaceAll(1, "one"); 功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM