2

我有一个与正则表达式匹配的文本,如下所示:

====================
    DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

    Copyright 2008-2009 Company, Inc. All rights reserved.


    The contents of this file are subject to the terms of the Common Development
    and Distribution License("CDDL") (the "License"). You may not use this file
    except in compliance with the License.

    You can obtain a copy of the License at https://oss.oracle.com/licenses/CDDL
    See the License for the specific language governing permissions and limitations
    under the License.

    When distributing the Covered Code, include this CDDL Header Notice in each file
    and include the License file at https://oss.oracle.com/licenses/CDDL.
    If applicable, add the following below this CDDL Header, with the fields
    enclosed by brackets [] replaced by your own identifying information:
    "Portions Copyrighted [year] [name of copyright owner]"
    ====================

    Copyright 2011-2013 Company. All rights reserved.

=========== 之间的部分是静态的,永远不会改变,所以我可以以静态方式搜索这个表达式,但它不是一个格式良好的正则表达式,我怎样才能让 = 之间的所有文本========== 正则表达式中的静态?

4

2 回答 2

4

\Q如果您实际上不能编写代码,而只能编写正则表达式,则可以使用and关闭模式特定部分的所有元字符\E

startOfRegex\Q============...\EendOfRegex

这样, and 之间的部分\Q可以\E包含任意正则表达式元字符(如括号、方括号、星号和反斜杠等等),而startOfRegexandendOfRegex可以是正常和任意正则表达式模式。

\E只有当字符串包含反斜杠或以反斜杠结尾时,您才会遇到问题。在这种情况下,Tim Pietzker'sPattern.quote是唯一通用的方法。

于 2013-06-28T12:53:20.417 回答
3

Netbeans 使用 Java,对吗?然后你可以使用

String regex = Pattern.quote(my_verbatim_string);

正确转义所有正则表达式元字符。

(?s)={20}.*?={20}但很有可能,使用正则表达式来查找 s 之间的所有文本====================,然后进行严格的相等比较会是一个更好的主意。

于 2013-06-28T12:42:04.567 回答