How to match “any character” in regular expression?

前端 未结 11 610
忘了有多久
忘了有多久 2020-11-27 09:23

The following should be matched:

AAA123
ABCDEFGH123
XXXX123

can I do: \".*123\" ?

相关标签:
11条回答
  • 2020-11-27 10:18

    [^] should match any character, including newline. [^CHARS] matches all characters except for those in CHARS. If CHARS is empty, it matches all characters.

    JavaScript example:

    /a[^]*Z/.test("abcxyz \0\r\n\t012789ABCXYZ") // Returns ‘true’.
    
    0 讨论(0)
  • 2020-11-27 10:19

    The most common way I have seen to encode this is with a character class whose members form a partition of the set of all possible characters.

    Usually people write that as [\s\S] (whitespace or non-whitespace), though [\w\W], [\d\D], etc. would all work.

    0 讨论(0)
  • 2020-11-27 10:21

    No, * will match zero-or-more characters. You should use +, which matches one-or-more instead.

    This expression might work better for you: [A-Z]+123

    0 讨论(0)
  • 2020-11-27 10:25

    Yes that will work, though note that . will not match newlines unless you pass the DOTALL flag when compiling the expression:

    Pattern pattern = Pattern.compile(".*123", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(inputStr);
    boolean matchFound = matcher.matches();
    
    0 讨论(0)
  • 2020-11-27 10:26

    Specific Solution to the example problem:-

    Try [A-Z]*123$ will match 123, AAA123, ASDFRRF123. In case you need at least a character before 123 use [A-Z]+123$.

    General Solution to the question (How to match "any character" in the regular expression):

    1. If you are looking for anything including whitespace you can try [\w|\W]{min_char_to_match,}.
    2. If you are trying to match anything except whitespace you can try [\S]{min_char_to_match,}.
    0 讨论(0)
提交回复
热议问题