【问题标题】:Discrepancy in String array length with the same regex for the same input相同输入的相同正则表达式的字符串数组长度差异
【发布时间】:2015-04-27 04:10:06
【问题描述】:

以下代码在\n 上拆分字符串。对于小的输入,它确实有效,但对于相同的\n,长时间输入却无法正常工作。 为了调查相同的讨论here。 编写测试用例来验证行为。 对于\n,它按预期工作,因为当我尝试使用该程序时,答案中有一个建议以\\\\n 作为正则表达式进行测试,我在字符串数组长度计算方面有所不同。 下面有代码和我发现的差异。

public String[] token=new String[10];
public Addnumber(String input) {
    // TODO Auto-generated constructor stub
    this.token=input.split("\n");
    System.out.println("Inside constructor Length="+token.length);
    for(String s:token)
        System.out.println(s);
}

public static void main(String[] args) {
     String input="hi\niam\nhere";
     String input1="hi\niam\nhere";
     String input2="x = [2,0,5,5]\ny = [0,2,4,4]\n\ndraw y #0000ff\ny = y & x\ndraw y #ff0000";
     new Addnumber(input1);//calculating via constructor
     new Addnumber(input2);
     String[] istring=new String[10];
     //Calculating in main method
     // General expression of \n
     istring=input.split("\n");
     System.out.println("Length calcluated when \n as regex="+istring.length);
     for(String s:istring)
          System.out.println(s);    
     istring=input2.split("\\\\n");   //Check the  regex used here
     System.out.println("Length calcluated when \\\\n as regex="+istring.length);
     for(String s:istring)
         System.out.println(s);
}

关于执行这个程序输出如下

Inside constructor Length=3
hi
iam
here
Inside constructor Length=6
x = [2,0,5,5]
y = [0,2,4,4]

draw y #0000ff
y = y & x
draw y #ff0000
Length calcluated when 
as regex=3
hi
iam
here
Length calcluated when \\n as regex=1
x = [2,0,5,5]
y = [0,2,4,4]

draw y #0000ff
y = y & x
draw y #ff0000

请注意,当\n 是正则表达式时,字符串数组的长度是预期的,但是当\\\\n 作为正则表达式时,它显示长度为 1 但 内容拆分与以前相同。为什么正则表达式更改时长度计算会出现差异? :

【问题讨论】:

    标签: java regex


    【解决方案1】:

    我认为您对上述问题有点忽略了my answer 的观点。

    当使用split("\\n")分割字符串时,你用换行符分割它。

    当使用split("\\\\n") 分割字符串时,你是按文字序列\n 分割的。

    original question中,通过用户输入得到字符串,用户按字面意思输入\n。所以需要使用\\\\n来正确拆分。

    如果您想模拟文字 \n 用户输入,您的示例字符串需要如下所示:

    String input2 = "x = [2,0,5,5]\\ny = [0,2,4,4]\\n\\ndraw y #0000ff\\ny = y & x\\ndraw y #ff0000";
    

    如果您想知道为什么在上一个示例中,它显示长度为 1,但仍将字符串部分呈现在单独的行上:正在呈现的只是输入字符串中的换行符。

    【讨论】:

    • 这里的问题是为什么字符串数组长度值在能够成功拆分内容时显示为1?
    • 没有分割。您的输出仅呈现输入字符串中的换行符。
    • 感谢罗比的澄清。
    【解决方案2】:

    split("\n") 用换行符分割。你的字符串中有这个,所以你得到了一个拆分。

    split("\\\\n") 由反斜杠和换行符分割。正则表达式和Java字符串都有转义语义,所以字符串"\\\\n"实际上是正则表达式\\n(反斜杠和n)。 "\n" 在正则表达式中生成文字换行符; "\\n" 生成正则表达式 \n,正则表达式引擎将其读取为换行符。这两个都会给你换行符;但大概,您的字符串不包含反斜杠后跟n,因此split("\\\\n") 失败并返回您开始使用的一个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 2012-12-23
      • 2015-11-19
      • 2011-04-10
      相关资源
      最近更新 更多