正则表达式,以查看字符串是否包含模式

时间:2012-08-18 14:18:01

标签: java regex

我是正则表达式的新手,我发现很难完成这个简单的任务。整个字符串看起来像

debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: read PEM private key done: type RSA
debug1: Enabling compression at level 6.
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: Sending subsystem: sftp
Can't ls: "/home/dev/customer/*.out" not found
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
debug1: fd 0 clearing O_NONBLOCK
debug1: fd 2 clearing O_NONBLOCK
debug1: Transferred: stdin 0, stdout 0, stderr 0 bytes in 0.1 seconds
debug1: Bytes per second: stdin 0.0, stdout 0.0, stderr 0.0
debug1: Exit status 0
debug1: compress outgoing: raw data 343, compressed 184, factor 0.54
debug1: compress incoming: raw data 860, compressed 430, factor 0.50

我只需要检查此字符串中是否存在*.out/text" not found之类的内容。它确实存在于这种情况下,但我没有得到输出为真

我使用的正则表达式.*\*\..*" not found.*不起作用。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

使用字符串匹配

你真的不需要正则表达式。一个简单的字符串匹配将工作得很好,也更快!例如:

$ fgrep '.out" not found' /tmp/foo
Can't ls: "/home/dev/customer/*.out" not found

如果你真的想要一个正则表达式

如果你坚持使用,你可以使用正则表达式,但是对于你的用例它不会更好。不过,这里是:

$ egrep '\.out" not found' /tmp/foo
Can't ls: "/home/dev/customer/*.out" not found

正则表达式的技巧是确保只匹配最小必要文本以确保正确匹配,而不是尝试使用正则表达式标记构造整行。在这种情况下,简单就更好了。

答案 1 :(得分:0)

import java.util.regex.*;

class Main
{
  public static void main (String[] args) throws java.lang.Exception
  {
    java.io.BufferedReader in = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
    String input = "";
    String s;
    while ((s = in.readLine()) != null && s.length() != 0) input += s;
    Pattern pattern = Pattern.compile("\\*\\.(?:out|text)\\\"\\s+not\\sfound");
    Matcher  matcher = pattern.matcher(input);
    if (matcher.find())
      System.out.println("Match found");
  }
}

测试此代码here

答案 2 :(得分:-1)

这适用于多行和单行模式

(^.*?|.*?)\.(out|text).*?not found(.*?|.*?$)
相关问题