有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中识别一串字符串中的编号系统/序列/模式

我有一串这样的弦

1. INTRODUCTION
2. BASICS
3. ADVANCED CONCEPTS
4. EXAMPLES

上面的每一行都是一个单独的字符串。相同的字符串可以如下所示-

A. INTRODUCTION
B. BASICS
C. .. 

或作为

I) INTRODUCTION
II) BASICS
III) ...

或作为

10.01 INTRODUCTION
10.02 BASICS
...

因此,我试图识别(并可能消除)这些字符串之间存在的任何类型(数字、浮点数、罗马数字和完全未知的类型)的序列。 在java中实现这一点的最佳方法是什么


共 (1) 个答案

  1. # 1 楼答案

    你是想在中间的空间分裂吗

    public class TestApp {
        public static void main(String[] args)  {
            String[] strings = new String[] {
                    "1. INTRODUCTION",
                    "2. BASICS",
                    "3. ADVANCED CONCEPTS",
                    "4. EXAMPLES"};
    
            for(String string : strings) {
                String[] tokens = string.split(" ");
                System.out.println("[" + string + "][" + tokens[0] + "][" + tokens[1] + "]");
            }
        }
    }
    

    输出为

    [1. INTRODUCTION][1.][INTRODUCTION]
    [2. BASICS][2.][BASICS]
    [3. ADVANCED CONCEPTS][3.][ADVANCED]
    [4. EXAMPLES][4.][EXAMPLES]
    

    如果您知道您的模式,请使用这样一个简单的设计模式

    public class TestApp {
    
      private static IPatternStripper[] STRIPPERS = new IPatternStripper[] {
        new NumeralStripper()
        // more types here ...
      };
    
      public static void main(String[] args)  {
    
        String[] strings = new String[] {
            "1. INTRODUCTION",
            "2. BASICS",
            "3. ADVANCED CONCEPTS",
                "4. EXAMPLES"};
    
        for(String string : strings) {
          IPatternStripper foundStripper = null;
          for(IPatternStripper stripper : STRIPPERS) {
            if(stripper.isPatternApplicable(string)) {
              foundStripper = stripper;
              break;
            }
          }
          if(foundStripper != null) {
            System.out.println("SUCCESS: " + foundStripper.stripPattern(string));
          }
          else {
            System.out.println("ERROR: NO STRIPPER CAN PROCESS: " + string);
          }
        }
      }
    }
    
    interface IPatternStripper {  
      public boolean isPatternApplicable(String line);  
      public String stripPattern(String line);
    }
    
    class NumeralStripper implements IPatternStripper {
    
      @Override
      public boolean isPatternApplicable(String line) {
        boolean result = false;
    
        // code here checks whether this stripper is appropriate    
        return result;
      }
    
      @Override
      public String stripPattern(String line) {
        String value = line;
        // code here to do your stripping
        return value;
      }
    }