【问题标题】:Substring String until first letter子字符串字符串直到第一个字母
【发布时间】:2020-02-02 16:58:34
【问题描述】:

我需要substring 字符串(用户输入)直到第一个字母。我不能在indexOf 中使用正则表达式。我试过这样:

String stringValue = input.substring(0, input.indexOf([^\\d.]));

【问题讨论】:

  • 这样的? ^\W* 模式 - 字符串 ^ 的开头后跟零个或多个 非字母
  • 你能补充几个例子吗?
  • @DmitryBychenko 它返回StringIndexOutOfBoundsException

标签: java regex substring


【解决方案1】:

相当简单的解决方案,但这可能有效:

  public static void main(String[] args) {
    String s = "1248941e189d1";
    int index = -1, i = 0;

    for (char c : s.toCharArray()) {
        if (Character.isLetter(c)) {
            index = i;
            break;
        }
        i++;
    }
    System.out.println(s.substring(0, index));
  }

您首先查找字符串中的第一个字母,然后您只需获取子字符串直到它的索引。

【讨论】:

    【解决方案2】:

    使用正则表达式查找String 中的第一个字母;没什么太花哨的,没有技巧

    private static final Pattern LETTER = Pattern.compile("[a-zA-Z]");  
            // or "\\p{Alpha}", or "\\p{L}", or whatever is needed
    
    // inentionally throws NullPointerException if argument is null
    public static int findFirstLetter(String text) {
        var matcher = LETTER.matcher(text);
        if (matcher.find()) {
            return matcher.start();
        } else {
            return -1;  // or throw exception, or ...
        }
    }
    

    我更喜欢这个,因为它完全符合我的要求(我不想 splitreplace 任何东西,只是 find

    【讨论】:

      【解决方案3】:

      如果你确定你的字符串以数字开头,你可以简单地拆分它:

      String input = "1234x";
      System.out.println(input.split("[^\\d.]")[0]); //1234
      

      请注意,如果它不以数字开头,则每个不符合 \d 的字符的第一个索引将为空。

      【讨论】:

        【解决方案4】:

        如果您想要字母第一次出现之前的内容,您可以使用捕获组来匹配除使用 \P{L} 的字母之外的任何字符,然后使用 \p{L} 匹配字母。

        ^(\P{L}+)\p{L}
        
        • ^ 字符串开始
        • ( 捕获第 1 组
          • \P{L}+ 匹配 1+ 次 \p{L} 的反面
        • )
        • \p{L} 匹配任何语言的任何字母

        Regex demo | Java demo

        Pattern pattern = Pattern.compile("^(\\P{L}+)\\p{L}");
        Matcher matcher = pattern.matcher("1234x");
        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
        

        输出

        1234
        

        【讨论】:

          【解决方案5】:

          这可能对你有用:

          jshell> s
          s ==> " 123abc"
          
          jshell> s.replaceAll("[a-zA-Z]{1}.*", "")
          $6 ==> " 123"
          

          这里我们匹配一个字母后跟任何字符,并将匹配替换为空字符串。

          【讨论】:

          • 不能用这个东西,因为用户可以输入“123abc123”。
          • 在这种情况下你想要什么“123abc123”?如果你想要两个数字,你可以使用'split'方法。
          • 只需要前 123 个
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-12
          • 1970-01-01
          • 2013-09-24
          • 1970-01-01
          • 1970-01-01
          • 2021-04-15
          相关资源
          最近更新 更多