简体   繁体   English

如何匹配任何符号,包括行终止符?

[英]How to match any symbol including a line terminator?

I have a text "text abc". 我有一个文本“文本abc”。 When I use the "(.+) abc" pattern, I'm found a match "text", it is ok. 当我使用“(。+)abc”模式时,我找到了一个匹配的“文本”,没关系。 But if I use a second pattern, "([.]{1,}) abc", matcher doesn't found any match. 但是,如果我使用第二个模式“([.. {1,})abc”,则匹配器找不到任何匹配项。 Why? 为什么?

I want use brace [], because I want use also a break line symbol (eg, now I can't match "text \\n abc" with first pattern. 我想使用大括号[],因为我还想使用换行符(例如,现在我无法将“ text \\ n abc”与第一个模式匹配)。

Sorry for my bad English 对不起,我的英语不好

See also DOTALL pattern: https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL 另请参见DOTALL模式: https ://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL

My code: 我的代码:

    String text = "text abc";
    Pattern pattern = Pattern.compile("(.+) abc");
    Matcher m = pattern.matcher(text);
    while (m.find()) {
        System.out.println(m.group(1));
    }

PS: my goal is using somesing like "([.\\n]{1,}) abc" pattern. PS:我的目标是使用“([..n] {1,})abc”模式。

Its not clear what you are trying to match, but if i understand correctly your problem is with "text \\n abc". 目前尚不清楚您要匹配的内容,但是如果我正确理解您的问题是“ text \\ n abc”。 That's because of the newline to fix this use this 那是因为换行来解决这个问题

Pattern pattern = Pattern.compile("(.+) abc", Pattern.DOTALL);

Pattern.DOTALL flag for "." “。”的Pattern.DOTALL标志。 to match even \\r or \\n. 甚至匹配\\ r或\\ n。

Right now, the pattern ([.\\n]{1,}) abc is rather backwards. 现在,模式([.\\n]{1,}) abc相当倒退。 First off, the {1,} is identical to + , so this pattern is really ([.\\n]+) abc . 首先, {1,}+相同,因此此模式实际上是([.\\n]+) abc Secondly, as stated in the Oracle regex tutorials: 其次,如Oracle regex教程所述:

Note: In certain situations the special characters listed above will not be treated as metacharacters. 注意:在某些情况下,上面列出的特殊字符将不被视为元字符。

In the case [.] , . 在这种情况下[.] . is no longer a regex meta character. 不再是正则表达式元字符。 You can verify this by testing the pattern against the string "test . abc" , which will group "." 您可以通过针对字符串"test . abc"测试模式来验证这一点,该字符串将对"."分组"." .

To enable the DOTALL flag, just add the parameter to the regex or you can add the option as a parameter: 要启用DOTALL标志,只需将参数添加到正则表达式中,或者您可以将选项添加为参数:

Pattern pattern = Pattern.compile("(?s)(.+) abc")

Pattern pattern = Pattern.compile("(.+) abc", Pattern.DOTALL)

Note reference 注意事项

Full list of flags and other useful information 标志和其他有用信息的完整列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM