我有一个字符串列表,例如(q1,0)->(q2,_,R)
,我需要选择q1、0,然后选择q2,_,R。我会使用.substring(enter numbers)
,但是这些字符的位置在列表中会改变。例如,我也有(q11,1)->(q11,1,L)
。因此,虽然对于第一个字符串,我可以执行.substring(1,3)来获取q1,然后可以执行.substring(4,5)来获取0,但对于其他字符串我不能执行相同操作。
我的想法是,我可以找到字符串的长度,然后为每个长度使用具有不同数字的子字符串。我想知道是否有更简单的方法来做到这一点。
答案 0 :(得分:0)
您可以将正则表达式设为\\(([^)]+)\\)
public static void main(String[] args) {
String str = "(q1,0)->(q2,_,R)";
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(str);
while(m.find()) {
System.out.println(m.group(1));
}
}
输出:
q1,0
q2,_,R
正则表达式可以读取如下:
\\( - character (
( - start match group
[- one of these characters
^ - not the following character
) - with the previous ^, this means "every character except )"
+ - one of more of the stuff from the [] set
) - stop match group
\\) - literal closing paranthesis