【问题标题】:Testing for 'noise' at the start and end of a segment without regex在没有正则表达式的段的开头和结尾测试“噪音”
【发布时间】:2013-12-10 12:30:28
【问题描述】:

我正在编写将一段数据作为字符串接收的代码。该字符串将具有不同的大小,但始终以相同的字符开头和结尾(开始:'<s-' 结束:'-e>')。我想防止用户在段的开始和结束之前输入无效字符时出错。例如

"fdslkjds<s-hello-e>"
"<s-there-e>dfsad"
"eiend<s-john-e>dfafsd"

我知道这可以通过导入正则表达式库(模式和匹配)来完成。但我想在不使用这些库的情况下尝试这个。还有其他方法吗?我一直在寻找 String 库,但找不到我需要的确切方法。

【问题讨论】:

  • 这里避免使用正则表达式会增加很多工作量。为什么要避开它们?
  • 不,它不会增加很多工作,@user270349,看看 Ryan Carlsons 的回答。
  • @Ingo 你是对的。我正在考虑消除噪音,而不是对其进行测试。我的错。

标签: java regex string match


【解决方案1】:

我建议你看看StringsstartsWith()endsWith() 方法。

我还建议您自己编写代码,但如果您不想为此烦恼,这里有一些应该可以工作的代码:

String input = [your code here]
while(!input.startsWith("<s-") || !input.endsWith("-e>"))
{
    System.out.println("Error! Invalid input! Please try again:");
    input = [your code here]
}

【讨论】:

    【解决方案2】:

    正如戴帽子的家伙所说,startsWithendsWith 等字符串的函数足以实现您的目标。

    if(!userString.startsWith("<s-") || !userString.endsWith("-e>")) {
      throw new Exception("Please do not enter invalid characters before the start and the end of the segment");
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用indexOflastIndexOf 来查找&lt;s--e&gt; 在字符串中的位置,并使用substring 来提取正确的子字符串,而不会产生任何“噪音”。

      String s = "eiend<s-john-e>dfafsd";
      String s2 = s.substring(s.indexOf("<s-"), s.lastIndexOf("-e>") + 3);
      

      【讨论】:

        猜你喜欢
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-07
        • 2015-12-16
        • 2013-08-04
        • 1970-01-01
        • 2018-02-21
        相关资源
        最近更新 更多