【问题标题】:Process expression string in Java [toLower,toUpper and concat]Java中的处理表达式字符串[toLower,toUpper和concat]
【发布时间】:2019-07-16 09:29:22
【问题描述】:

我有一个带有toLowertoUpperconcat 函数的任意组合的正则表达式,例如。 inputString = concat(toLower(concat("ABC","xyz")),toUpper("pqr"))outputString = abcxyzPQR

表达式输入字符串可以有三个函数[toLower,toUpperconcat]的多种组合。

如何在 Java 中使用以上 3 个函数的任意组合来处理字符串?

【问题讨论】:

  • 你能添加你的代码并指出你的问题在哪里吗?
  • 如果任何组合和嵌套级别是可能的,那么您可能希望为所有可能的变体和该语法的解析器创建正确的 grammar 而不是正则表达式。我听说github.com/antlr/antlr4 是解决这类问题的好工具。

标签: java regex string combinations permutation


【解决方案1】:

使用下面的代码:

import java.util.Random;

    public class RandomCombination
    {

    public static void main(String args [])
    {
    Random randomGenerator=new Random(); // We will randomize between 1 to 3. We are adding in the random coz next(3) will randomize from 0-2
     String outputString= randomize("ABC",randomGenerator.nextInt(3)+1).concat(randomize("xyz",randomGenerator.nextInt(3)+1)).concat(randomize("pqr",randomGenerator.nextInt(3)+1));

     System.out.println(outputString);
    }
    static String randomize(String inputString, int ran )
    {
    String outuput;
    switch(ran){
        case 1:
        outuput=inputString.toUpperCase(); // if 1 use upper
        break;
        case 2:
        outuput= inputString.toLowerCase();  // if 2 use lower
        break;  
        default:
        outuput=inputString;  // if 3 don't do a thing
        }

        return outuput;
    }
    }

Sample output:
abcXYZPQR
abcxyzpqr
ABCXYZpqr
abcxyzPQR
abcXYZPQR

【讨论】:

  • 没有。我不想要随机输出。假设我的输入字符串是 "concat(toLower(concat("ABC","xyz")),toUpper("pqr"))" 那么 outputString 应该是 abcxyzPQR ....所以可以有 toLower,toUpper 和连接任何级别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2022-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多