在Java中忽略带有正则表达式模式的空格和注释

时间:2016-08-23 15:11:25

标签: java regex

我正在开发一个Java程序,我需要帮助来创建这个模式:

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Pragma","no-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setDateHeader("Expires",0);
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    String toPrint = "";
    toPrint += "First name: ";
    toPrint += request.getParameter("firstName");
    out.write(toPrint);
}

我想忽略第一组之后的所有空格,例如,如果名称为“George P”,则应仅计算“George P”。 此外,我想考虑评论字符*,忽略此后的所有字符。如果没有*并且发现许多空格,则匹配器应该失败。

2 个答案:

答案 0 :(得分:2)

<强> UPDATE2
RE:DC正则表达式,每条评论。

^\s*(DC\s)((\d+)(\.)?(\d+)?)(?=\s*(?:\*|$))

 ^                             # BOS
 \s*                           # Optional whitespace's

 ( DC \s )                     # (1), DC + single whitespace
 (                             # (2 start)
      ( \d+ )                       # (3), 1 or more Digits
      ( \. )?                       # (4), Optional dot .
      ( \d+ )?                      # (5), Optional 0 or more Digits
 )                             # (2 end)

 (?=                           # Lookahead qualifier Assertion
      \s*                           # Optional whitespace's
      (?:                           # ---------------------
           \*                            # Asterisk (comment)
        |                              # or,
           $                             # End of string
      )                             # ---------------------
 )

<强>更新
组1中包含星号 NOT

I\sam\s([^*]*)(?:(?<!\s)|(?<=I\sam\s))

解释

 I \s am \s                    # 'I am '

 ( [^*]* )                     # (1), Capture after that, but not asterisk or after

 (?:                           # Trimming
      (?<! \s )                     # Trim, no wsp behind
   |                              # or,
      (?<= I \s am \s )             # Just 'I am ' behind
 )

第1组中包含的星号 IS

I\sam\s([^*]*\*?)(?:(?<!\s)|(?<=I\sam\s))

注意 - 修正条件使这个正则表达式更复杂。最好不要在正则表达式中修剪,但是在匹配后使用语言api来修剪捕获1的内容。

解释

 I \s am \s                  # 'I am '

 ( [^*]* \*? )               # (1), Capture after that, but not after asterisk

 (?:                         # Trimming
      (?<! \s )                   # Trim, no wsp behind
   |                            # or,
      (?<= I \s am \s )           # Just 'I am ' behind
 )

答案 1 :(得分:0)

使用以下正则表达式:

"I\\sam\\s[a-zA-Z]+\\s+[a-zA-Z]+"

您的问题可能是,您必须转义转义字符,因为\sPattern特殊字符。不是java的。这将匹配:

I am George P
I am Tom     D
I am sdawawe x

赢得不匹配:

I am    George P
I   am Geor s

这是你想要的吗?