3

我需要检查具有以下任一模式的行:

preposition word ||| other words or what ever
word preposition ||| other words or what ever

介词可以是列表中的任何一个词,例如 {de, à, pour, quand, ...} 这个词可以是介词也可以不是。

我尝试了很多模式,如下所示

File file = new File("test.txt");   
Pattern pattern = Pattern.compile("(\\bde\\b|\\bà\\b) \\w.*",Pattern.CASE_INSENSITIVE);          
String fileContent = readFileAsString(file.getAbsolutePath());           
Matcher match = pattern.matcher(fileContent);
System.out.println( match.replaceAll("c"));

此模式匹配一​​个介词,在管道之前至少跟一个单词。我想要的是匹配一个介词,然后在管道之前只有一个单词。我尝试了以下模式

Pattern pattern = Pattern.compile("(\\bde\\b|\\bla\\b)\\s\\w\\s\\|.*",Pattern.CASE_INSENSITIVE);

不幸的是,这种模式不起作用!

4

2 回答 2

1

为了简洁起见,我将使用prepto stand in 作为我们可以处理的介词:

Pattern pattern = Pattern.compile("(?:(?:\\bprep\\b \\w+)|(?:\\w+ \\bprep\\b)).*",
                                 Pattern.CASE_INSENSITIVE);    

(?:...)说要分组但捕获
\\bprep\\b确保prep仅当它单独时才匹配,即它不会匹配最后的preposition
\\w+需求1 或更多 [a-zA-Z_0-9]
.*与两组括号一起使用

编辑(回应评论):
"^(?:(?:\\bprep\\b \\w+)|(?:\\w+ \\bprep\\b)).*" 正在工作,你很可能遇到这样的情况:

String myString = "hello prep someWord mindless nonsense";

匹配,因为这被第二种情况捕获:(?:\\w+ \\bprep\\b)).*.

如果你尝试这些,你会发现^实际上是有效的:

String myString = "egeg  prep rfb tgnbv";

这与第二种情况不匹配,因为 后面有 2 个空格"egeg",所以它只能匹配第一种,但由于^. 此外:

String myString = "egeg hello prep rfb tgnbv";

我们已经确定这样的案例不会匹配第一个,它也不会匹配第二个,这意味着它^实际上是有效的。

于 2013-08-05T23:54:06.923 回答
0

我感谢大家的回答。事实上,正如@Pshemo 所说,我只需要在 \w 之后添加 +。我认为 \w 表示单词。它现在可以使用以下代码:

File file = new File("test.txt");   
Pattern pattern = Pattern.compile("(\\bde\\b|\\bla\\b)\\s\\w+\\s\\|.*|\\w+\\s(\\bde\\b|\\bla\\b)\\s\\|.*",Pattern.CASE_INSENSITIVE)
String fileContent = readFileAsString(file.getAbsolutePath());           
Matcher match = pattern.matcher(fileContent);
System.out.println( match.replaceAll(""));

例如,作为输入,我有以下几行:

世界|||这里的东西|||这里的其他东西

关于|||这里的东西|||这里的其他东西的世界

另一个例子||| 这里有东西|||这里有其他东西

最后和最后一个例子|||这里的东西|||这里的其他东西

然后,假设介词列表是 {the, about},输出将是:

另一个例子||| 这里有东西|||这里有其他东西

最后和最后一个例子|||这里的东西|||这里的其他东西

如您所见,我只想匹配前两行并删除它们。

于 2013-08-06T02:47:31.493 回答