English 中文(简体)
使用正则表达式在java中拆分字符串需要帮助
原标题:Need help to split string in java using regex
  • 时间:2011-05-25 06:25:38
  •  标签:
  • java
  • regex

我有一个类似“portal100common2055”的字符串。

我想把它分成两部分,第二部分应该只包含数字。

“portal200511sbet104”将变为《portal200511sbet》

你能帮我实现这一点吗?

问题回答

像这样:

    Matcher m = Pattern.compile("^(.*?)(\d+)$").matcher(args[0]);
    if( m.find() ) {
        String prefix = m.group(1);
        String digits = m.group(2);
        System.out.println("Prefix is ""+prefix+""");
        System.out.println("Trailing digits are ""+digits+""");
    } else {
        System.out.println("Does not match");
    }
String[] parts = input.split("(?<=\D)(?=\d+$)");
if (parts.length < 2) throw new IllegalArgumentException("Input does not end with numbers: " + input);
String head = parts[0];
String numericTail = parts[1];

这个更优雅的解决方案使用regex的向后看向前看

说明:

  • (?<=\D) means at the current point, ensure the preceding characters ends with a non-digit (a non-digit is expressed as D)
  • (?=\d+$) means t the current point, ensure that only digits are found to the end of the input (a digit is expressed as d)

这将只在您想要划分输入的所需点处为true





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...