如何在字母和数字之间(或在数字和字母之间)拆分字符串? [英] How to split a string between letters and digits (or between digits and letters)?
问题描述
我正在尝试找出一种在 java 中按照这样的模式拆分字符串的方法:
I'm trying to work out a way of splitting up a string in java that follows a pattern like so:
String a = "123abc345def";
结果应该如下:
x[0] = "123";
x[1] = "abc";
x[2] = "345";
x[3] = "def";
但是,我完全不知道如何实现这一目标.请问有人可以帮我吗?我曾尝试在网上搜索类似的问题,但很难在搜索中正确表达.
However I'm completely stumped as to how I can achieve this. Please can someone help me out? I have tried searching online for a similar problem, however it's very difficult to phrase it correctly in a search.
请注意:字母的数量&数字可能会有所不同(例如,可能有一个像 '1234a5bcdef' 这样的字符串)
Please note: The number of letters & numbers may vary (e.g. There could be a string like so '1234a5bcdef')
推荐答案
你可以尝试在 (?<=D)(?=d)|(?<=d)(?=D)
,例如:
You could try to split on (?<=D)(?=d)|(?<=d)(?=D)
, like:
str.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)");
它匹配数字和非数字之间的位置(以任何顺序).
It matches positions between a number and not-a-number (in any order).
(?<=D)(?=d)
- 匹配非数字 (D
) 和数字 (>d
)(?<=d)(?=D)
- 匹配数字和非数字之间的位置.
(?<=D)(?=d)
- matches a position between a non-digit (D
) and a digit (d
)(?<=d)(?=D)
- matches a position between a digit and a non-digit.
这篇关于如何在字母和数字之间(或在数字和字母之间)拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!