我可以在Java中将正则表达式与子串()结合起来吗?

时间:2013-12-29 15:15:21

标签: java regex substring

我们正在将文档库导入SharePoint,我正在使用我编写的java程序来构建这些文档的元数据。我需要做的一件事是确定文档是否有交叉引用的文档。此条件定义为在文档名称中包含短语“see”。但是,命名约定不存在,并且存在以下所有变体:

document_see_other_document.doc
document_-_see_other_document.doc
document_(see_other_document).doc
document_[see_other_document].doc
document_{see_other_document}.doc

我创建了一个默认为的变量:String xref = "no cross reference";如果文件名中有String子字符串,我想将此"see_other_document"设置为see <other document>

我的计划是查找see_的实例,将其用作子字符串的起点,以.结尾,不包含。但是我想要消除可能存在的任何特殊字符。在我的上述情况中,我想返回other_document的五个实例,而不是other_document)等。

我的想法是将子字符串拉入变量,然后使用正则表达式[^a-zA-Z0-9]并替换第二个字符串变量中的非字母数字字符,但是有更好,更优雅的方法来修饰这只猫吗? / p>

伪代码:

if (filename.indexOf("see_">-1) {
    String tempFilename = fileName.substring(indexOf("see_")+4,indexOf("."-1));
    xref = tempFilename.replaceAll("[^a-zA-Z0-9]","");
    } else {
    xref;
}

4 个答案:

答案 0 :(得分:1)

您可以将正则表达式与可选部分一起使用。以下片段显示了如何。 (?:something)是非捕获组:

    Pattern patt = Pattern.compile("_(?:\\-_)?(?:\\(|\\[|\\{)?see_([a-zA-Z_0-9]+)(?:\\)\\}|\\])?");

    for (String filename : new String[] {"document_see_other_document.doc", "document_-_see_other_document2.doc", 
            "document_(see_other_3document).doc", "document_[see_other_4document].doc", "document_{see_other_document5}.doc", "blacksee_other_document.doc"}){
        Matcher m= patt.matcher(filename);

        if (m.find()){
            System.out.println(m.group(1));
        }
        else {
            System.out.println("negative");
        }

    }

答案 1 :(得分:0)

由于Steve McConnell suggests在一行中写一些内容并不是更优雅。我相信你做事的方式是最优雅的。

让我们假设您找到了一种使用复杂正则表达式在一行中完成所有这些事情的神奇方法。

代码会更具可读性吗? 当然不是。使用复杂的正则表达式远非易读。通过阅读正则表达式,没有人会理解你想做什么。

代码是否更易于维护? 当然不是。更改正则表达式以执行稍微不同的匹配可能是一项非常繁琐的任务。与调试相同。

代码会更快吗? 可能是,可能不是。你必须测试它。然而,性能差异不是你的目标。

因此,我认为你的代码足够优雅,我不打算改变它。

希望我帮忙!

答案 2 :(得分:0)

在所有示例中,垃圾字符出现在消息之前和之后(see_other_document)。消息本身完全由单词字符组成(即没有标点符号,也没有空格)。我们可以指望所有这些条件吗?如果可以的话,这应该是正确的:

    String result = source.replaceAll(
         "(document_)[\\W_]*+(see_\\w++)[^\\w.]*+(\\.doc)",
         "$1$2$3");

基本的想法是,如果你不想要它,不要捕获它。

答案 3 :(得分:0)

你的代码实际上很好,但你可以试试这个:

if(filename.indexOf("see_">=0){
    String temp=filename.substring(filename.indexOf("see_")+4,filename.length()-4);
//                      if there exist '.' in "other_document"^
    xref=temp.replaceAll("[^\\p{L}0-9]","");
//                          ^here for unicode character
} else{
    xref;
}