【问题标题】:How can i grab numbers out of strings when the length of the string changes?当字符串的长度发生变化时,如何从字符串中提取数字?
【发布时间】:2020-03-20 04:31:38
【问题描述】:

我有一个字符串列表,例如(q1,0)->(q2,_,R),我需要选择 q1、0 和 q2,_,R。我会使用.substring(enter numbers),但这些字符在列表中的位置会发生变化。例如,我也有(q11,1)->(q11,1,L)。所以,虽然对于第一个字符串,我可以使用 .substring(1,3) 来获取 q1,然后使用 .substring(4,5) 来获取 0,但我不能对其他字符串执行相同操作。

我想我可以找到字符串的长度,然后为每个长度使用具有不同数字的子字符串。我想知道是否有更简单的方法来做到这一点。

【问题讨论】:

  • 使用正则表达式消除 ( ) -> 等字符。
  • 举个具体的例子说明你想要什么

标签: java string substring


【解决方案1】:

您可以将正则表达式设为\\(([^)]+)\\)

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

【讨论】:

  • @Austin Story,你能检查一下这是你期望的还是别的什么?
  • 看起来不错!我过去使用过正则表达式,但很难理解它。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
  • 2022-08-10
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2020-07-02
相关资源
最近更新 更多