使用正则表达式拆分不正确返回数字
Split with Regex not returning properly with numbers
我正在尝试使用正则表达式将字符串一分为二。例如,输入字符串的格式为 "Something something something 30min"
。在这种格式中,它总是以分钟为单位的时间结束。我需要将其拆分为 "Something something something"
和 "30min"
。我现在的解决方案是:
String[] separatedLine = line.split("(?=(\d)+)" );
但随后我得到 "Something something something" 和 3。如果我改为尝试:
String[] separatedLine = line.split("(?=(\d\d))" );
它有效,但我不知道我的号码的大小,据我所知可以是 5 也可以是 180。我尝试了许多不同的组合,但 none 似乎对每种情况都有用。
使用单词边界尝试这个正则表达式:
String[] separatedLine = line.split("(?=\b\d)" );
这将在 30
之前拆分,但不会在 3
和 0
之间拆分。
按照数字前面的space拆分即可。
String[] separatedLine = line.split("\s+(?=\d+)" );
或
如有必要,请在号码后添加 min
。
String[] separatedLine = line.split("\s+(?=\d+min)" );
代码:
String s = "Something something something 30min";
String[] parts = s.split("\s+(?=\d+)");
System.out.println(Arrays.toString(parts));
输出:
[Something something something, 30min]
你可以这样做:
String[] split = "Something something something 30min".split("(?<!\d)(?=\d+)");
只要出现一个数字前面没有另一个数字,它就会拆分您的 String
。
我正在尝试使用正则表达式将字符串一分为二。例如,输入字符串的格式为 "Something something something 30min"
。在这种格式中,它总是以分钟为单位的时间结束。我需要将其拆分为 "Something something something"
和 "30min"
。我现在的解决方案是:
String[] separatedLine = line.split("(?=(\d)+)" );
但随后我得到 "Something something something" 和 3。如果我改为尝试:
String[] separatedLine = line.split("(?=(\d\d))" );
它有效,但我不知道我的号码的大小,据我所知可以是 5 也可以是 180。我尝试了许多不同的组合,但 none 似乎对每种情况都有用。
使用单词边界尝试这个正则表达式:
String[] separatedLine = line.split("(?=\b\d)" );
这将在 30
之前拆分,但不会在 3
和 0
之间拆分。
按照数字前面的space拆分即可。
String[] separatedLine = line.split("\s+(?=\d+)" );
或
如有必要,请在号码后添加 min
。
String[] separatedLine = line.split("\s+(?=\d+min)" );
代码:
String s = "Something something something 30min";
String[] parts = s.split("\s+(?=\d+)");
System.out.println(Arrays.toString(parts));
输出:
[Something something something, 30min]
你可以这样做:
String[] split = "Something something something 30min".split("(?<!\d)(?=\d+)");
只要出现一个数字前面没有另一个数字,它就会拆分您的 String
。