Java REGEX to match an exact number of digits in a string

后端 未结 5 1795
天涯浪人
天涯浪人 2020-12-11 04:19

I tried to find the answer to my problem in the questions history but they just come back in more than one thousand and after scanning through a few tens of matching answers

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 04:46

    You can use the pattern (?, which means "a string-position that is not preceded by a digit; followed by exactly six digits; followed by a string-position that is not followed by a digit". (The notation (?, known as a negative lookbehind assertion, means "not preceded by ...". The notation (?!...), known as a negative lookahead assertion, means "not followed by ...". The notation \d means a digit. The notation {n} means "n times", so that e.g. \d{6} means "six digits".)

    That could look like this:

    final String number;
    {
        final Matcher m = Pattern.compile("(?

    Note: a previous version of this answer suggested the use of word boundaries, \b; but one of your comments suggests that the digits might be immediately preceded or followed by Traditional Chinese characters, which are considered word characters (and therefore wouldn't trigger a word boundary), so I've changed that.

提交回复
热议问题