Java Regexp to Match ASCII Characters

前端 未结 5 1105
甜味超标
甜味超标 2020-12-05 08:19

What regex would match any ASCII character in java?

I\'ve already tried:

^[\\\\p{ASCII}]*$

but found that it didn\'t match lots of

相关标签:
5条回答
  • 2020-12-05 09:00

    I think question about getting ASCII characters from a raw string which has both ASCII and special characters...

    public String getOnlyASCII(String raw) {
        Pattern asciiPattern = Pattern.compile("\\p{ASCII}*$");
        Matcher matcher = asciiPattern.matcher(raw);
        String asciiString = null;
        if (matcher.find()) {
            asciiString = matcher.group();
        }
        return asciiString;
    }
    

    The above program will remove the non ascii string and return the string. Thanks to @Oleg Pavliv for pattern.

    For ex:

    raw = ��+919986774157

    asciiString = +919986774157

    0 讨论(0)
  • 2020-12-05 09:08

    If you only want the printable ASCII characters you can use ^[ -~]*$ - i.e. all characters between space and tilde.

    https://en.wikipedia.org/wiki/ASCII#ASCII_printable_code_chart

    0 讨论(0)
  • 2020-12-05 09:15

    For JavaScript it'll be /^[\x00-\x7F]*$/.test('blah')

    0 讨论(0)
  • 2020-12-05 09:21

    I have never used \\p{ASCII} but I have used ^[\\u0000-\\u007F]*$

    0 讨论(0)
  • 2020-12-05 09:23

    The first try was almost correct

    "^\\p{ASCII}*$"
    
    0 讨论(0)
提交回复
热议问题