gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:40:35 27 4
gpt4 key购买 nike

我们正在将文档库导入到 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]并替换第二个字符串变量中的非字母数字字符,但是有没有更好、更优雅的方法来给这只猫换皮?

伪代码:

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

最佳答案

您可以将正则表达式与可选部分一起使用。以下片段展示了如何操作。 (?: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");
}

}

关于java - 我可以在 Java 中将正则表达式与 substring() 结合起来吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20826592/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com