【问题标题】:Remove leading trailing non numeric characters from a string in Java从Java中的字符串中删除前导尾随非数字字符
【发布时间】:2015-07-09 19:40:22
【问题描述】:

我需要分别从字符串中去掉第一个和最后一个数字的所有前导和尾随字符。

示例:OBC9187A-1%A
应该返回:9187A-1

如何在 Java 中实现这一点?

我知道正则表达式是解决方案,但我不擅长它。
我试过这个replaceAll("([^0-9.*0-9])","")
但它只返回数字并去除所有字母/特殊字符。

【问题讨论】:

  • Regex 将是一个很好的起点......
  • 你能edit你的问题并发布你的尝试吗?还要解释您在创建解决方案时遇到的问题。您只需要正则表达式即可找到digit one or more of any characters digit。这似乎不是很复杂的事情。
  • 我编辑了我的问题以包括我所做的事情。

标签: java regex


【解决方案1】:

这是一个使用regexjava 来解决您的问题的独立示例。我建议查看某种正则表达式教程 here 是一个不错的教程。

public static void main(String[] args) throws FileNotFoundException {
    String test = "OBC9187A-1%A";
    Pattern p = Pattern.compile("\\d.*\\d");
    Matcher m = p.matcher(test);

    while (m.find()) {
        System.out.println("Match: " + m.group());
    }
}

输出:

Match: 9187A-1

\d 匹配任何数字 .* 匹配任何数字 0 次或多次 \d 匹配任何数字。我们使用\\d 的原因是为了将\ 转义为Java,因为\ 是一个特殊字符......所以这个正则表达式将匹配一个数字,然后是任何数字,然后是另一个数字。这是贪婪的,因此它将花费最长/最大/最贪婪的匹配,因此它将获得第一个和最后一个数字以及介于两者之间的任何数字。 while 循环在那里,因为如果有超过 1 个匹配项,它将遍历所有匹配项。在这种情况下,只能有 1 个匹配项,因此您可以离开 while 循环或更改为 if,如下所示:

if(m.find()) 
{
    System.out.println("Match: " + m.group());
}

【讨论】:

  • 我在 replaceAll 中使用了类似的表达式,但它不起作用,只返回数字。
  • @user2166045 你用了什么表达方式?
  • @user2166045 在这种情况下,您可以使用replaceAll,下面有两个示例,但是由于您试图从String 中提取匹配项,因此我将使用PatternMatcher匹配您的String 的一部分。这使您可以根据需要保留原始的 String,或者您可以将其 myString = m.group(); 替换为匹配的 String
【解决方案2】:

这将从字符串 s 中去除前导和尾随非数字字符。

String s = "OBC9187A-1%A";
s = s.replaceAll("^\\D+", "").replaceAll("\\D+$", "");
System.out.println(s);
// prints 9187A-1

DEMO

正则表达式解释
^\D+

^ assert position at start of the string
\D+ match any character that's not a digit [^0-9]
     Quantifier: + Between one and unlimited times, as many times as possible

\D+$

\D+ match any character that's not a digit [^0-9]
     Quantifier: + Between one and unlimited times, as many times as possible
  $ assert position at end of the string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-05
    • 2014-08-09
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多