简体   繁体   English

Java-String.replaceAll返回不同的结果

[英]Java - String.replaceAll returns different result

Here's what I want, there's a string like, CHAR_27[19;50H and I want to get the numbers from the inside separately. 这就是我想要的,有一个字符串,例如CHAR_27[19;50H ,我想分别从内部获取数字。

// CHAR_27 = Character.toString( (char)27 );
// Or "\u001B"
String escapeString = "CHAR_27[19;50H";
String coord = escapeString.replaceAll("[^0-9;]", "");
List<String> coords = Splitter.on(";").splitToList(coord);

if (coords.size() != 2) continue;

rowIndex = Integer.parseInt(coords.get(0)) - 1;
colIndex = Integer.parseInt(coords.get(1)) - 1;

But sometimes it throws a NumberFormatException, invalid integer CHAR_27[19 . 但有时会抛出NumberFormatException, invalid integer CHAR_27[19

Mostly it works fine. 通常情况下,它运作良好。

Is there something wrong with my regex? 我的正则表达式有问题吗?

Or should I use StringUtils.removePattern() for a more consistent result? 还是应该使用StringUtils.removePattern()获得更一致的结果?

I got this report from Nokia_N1 and GT-810(rolex). 我从Nokia_N1和GT-810(rolex)获得了此报告。 Both of them are Android 5.1. 它们都是Android 5.1。

And I'm using Android API 24. 我正在使用Android API 24。

The code that you posted will not rise the mentioned exception (if the input is a single line string). 您发布的代码不会引发上述异常(如果输入是单行字符串)。

However your code contains some vulnerabilities: 但是,您的代码包含一些漏洞:

  • Orininally separate numbers can be joined by the expression 最初的数字可以由表达式连接
  • Empty strings can be created 可以创建空字符串

I would recommend to use: 我建议使用:

String escapeString = "CHAR_27[19;50H";
String[] coords = escapeString.split("[^0-9]+");

if (coords.length != 2) continue;

rowIndex = Integer.parseInt(coords[0]) - 1;
colIndex = Integer.parseInt(coords[1]) - 1;

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

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