简体   繁体   English

使用Regex过滤Java中的单词

[英]Using Regex to filter word in Java

I have a message that comes into the Android Device as text message which I read when it comes in like this Your OTP verification code is 5M67BX the OTP code isn't fixed. Your OTP verification code is 5M67BX一条消息,以短信形式发送到Android设备,当我Your OTP verification code is 5M67BX消息时,我会这样阅读。 Your OTP verification code is 5M67BXOTP code未固定。 It varies, if it were to be like that I'll just use a Regex Pattern of ([0-9]){1}([AZ]){1}([0-9]){2}([AZ]){1} But, it isn't always like that. 它变化,如果它是要这样我将只使用一个Regex Pattern([0-9]){1}([AZ]){1}([0-9]){2}([AZ]){1}但是,并非总是如此。 Sometimes all numbers. 有时是所有数字。 If you can share Pattern to filter the code out in Java would be appreciated. 如果可以共享Pattern以用Java过滤掉代码,将不胜感激。 Thanks 谢谢

If it is always a fixed length (6) and always at the end of the String, you could do: 如果它始终是固定长度(6),并且始终在String的末尾,则可以执行以下操作:

String s = "Your OTP verification code is 5M67BX";
String otpCode = s.substring(s.length() - 6);

Edit: With Regex this time... 编辑:这次用正则表达式...

String s = "Your OTP verification code is 5M67BX";  
String s2 = "Your updated OTP code is YW32R2 for phone verification";

Pattern p = Pattern.compile("([A-Z0-9]){6}");
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(m.group());
}
m = p.matcher(s2);
if (m.find()) {
    System.out.println(m.group());
}

Which outputs... 哪个输出...

5M67BX
YW32R2

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

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