在 Java 中使用 Regex 拆分字符串 [英] Splitting a string using Regex in Java

查看:68
本文介绍了在 Java 中使用 Regex 拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能帮我做一些正则表达式吗.

Would anyone be able to assist me with some regex.

我想把下面的字符串拆分成一个数字,字符串编号

I want to split the following string into a number, string number

"810LN15"

一种方法需要返回 810,另一种方法需要 LN,另一种方法应该返回 15.

1 method requires 810 to be returned, another requires LN and another should return 15.

唯一真正的解决方案是使用正则表达式,因为数字的长度会增加

The only real solution to this is using regex as the numbers will grow in length

我可以用什么正则表达式来适应这个?

What regex can I used to accomodate this?

推荐答案

String.split 不会给你想要的结果,我猜应该是 "810", "LN", "15",因为它必须寻找要拆分的标记并删除该标记.

String.split won't give you the desired result, which I guess would be "810", "LN", "15", since it would have to look for a token to split at and would strip that token.

尝试使用 PatternMatcher 代替,使用这个正则表达式:(\d+)|([a-zA-Z]+),它将匹配任何数字和字母序列并获得不同的数字/文本组(即AA810LN15QQ12345"将导致组AA"、810"、LN"、15"、QQ"和12345").

Try Pattern and Matcher instead, using this regex: (\d+)|([a-zA-Z]+), which would match any sequence of numbers and letters and get distinct number/text groups (i.e. "AA810LN15QQ12345" would result in the groups "AA", "810", "LN", "15", "QQ" and "12345").

示例:

Pattern p = Pattern.compile("(\\d+)|([a-zA-Z]+)");
Matcher m = p.matcher("810LN15");
List<String> tokens = new LinkedList<String>();
while(m.find())
{
  String token = m.group( 1 ); //group 0 is always the entire match   
  tokens.add(token);
}
//now iterate through 'tokens' and check whether you have a number or text

这篇关于在 Java 中使用 Regex 拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆