我正在导入一个包含"##,##"
行数的文件。每个数字可以是一位或两位数。
我想使用String.split(regex)
来获取没有相邻引号的两个数字。
了解我可以蚕食第一个和最后一个角色并使用非正则表达式分割,我希望有一个正则表达式可以使它更优雅。
建议?
编辑:
In: "12,3"
Out: 12
3
答案 0 :(得分:7)
如何使用正则表达式\"(d+),(d+)\"
。然后使用Pattern.matcher(input)
代替String.split
,并按Matcher.group(int)
获取您的数字。
请考虑以下代码段:
String line = "\"1,31\"";
Pattern pattern = Pattern.compile("\"(\\d+),(\\d+)\"");
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
int firstNumber = Integer.parseInt(matcher.group(1));
int secondNumber = Integer.parseInt(matcher.group(2));
// do whatever with the numbers
}
答案 1 :(得分:2)
您可以删除每行中的所有双引号字符,然后将字符串拆分为
String toSplit = "\"##,##\"";
String[] splitted = toSplit.replaceAll("\"", "").split(",");
使用\"
字符串中的toSplit
来模拟"##,##"
字符串。
答案 2 :(得分:0)
您也可以在引号处拆分,但这会产生一个长度为4的数组。不幸的是,无法拆分一个字符串并且删除其他字符使用String#split
在一次通话中使用相同的字符串。
作为替代方案,您可以使用Apache的StringUtils
:
String[] n = StringUtils.removeStart( StringUtils.removeEnd( "##,##", "\""), "\"").split(",");
编辑:作为附注,使用StringUtils
将允许在输入字符串的开头或结尾处缺少引号。如果您确定他们总是在场,那么简单substring(...)
就足够了。 (积分转到@Ingo)