我有一些模式/匹配器行,可以将输入字符串转换为如下形式:
1 3 Hi [2 1 4]
将其转换为这样的数组:
[0] => "1"
[1] => "3"
[2] => "Hi"
[3] => "2 1 4"
这是代码:
String input = sc.nextLine();
Pattern p = Pattern.compile("(?<=\\[)[^\\]]+|\\w+");
Matcher m = p.matcher(input);
List<String> cIn = new ArrayList<String>();
while(m.find()) cIn.add(m.group());
现在我意识到有时候可能会收到一些负值的输入,例如4 2 -1 2
。由于输入是字符串,我无法使用任何正则表达式来获取这个负数。
在下面的代码中,我使用了:
Integer.parseInt(cIn.get(0));
我需要将该字符串转换为整数,这正是我所需的。
你能想出一种方法让我将“-”字符和数字字符放在一起吗?然后,我只需检查是否有“-”字符来转换数字并乘以“-1”即可。(如果有更好的方法,我很乐意听取意见)。
通常情况下,请原谅我的英语。
[]
中的序列作为标记,即使它们包含空格。(但我也喜欢无正则表达式的方法!) - cheeken