0
String aStr="TEST-1-TV_50";
System.out.println(aStr.matches("^[A-Z0-9\\-\\_]+")); //TRUE.

But why this is not working..?

String aStr1= "$local:TEST12-1-TV_50 as xs:boolean";

int strtIndex=aStr.indexOf(":");
int endIndex=aStr.indexOf("as");

String extractedStr=aStr1.substring(strtIndex+1,endIndex);  //TEST12-1-TV_50


System.out.println(extractedStr.matches("^[A-Z0-9\\-\\_]+")); //FALSE. 

Why its giving result as false.???

4

2 回答 2

4

There's a trailing space in extractedStr.

So it contains "TEST12-1-TV_50 " (not that there's a space after the final 0).

You can either replace endIndex with aStr.indexOf(" as") (starting space) or simply call trim() on extractedStr:

String extractedStr=aStr1.substring(strtIndex+1,endIndex).trim();
于 2013-10-06T17:50:33.170 回答
2

您还需要在字符类中包含空格:

extractedStr.matches("^[A-Z0-9 _-]+"); // true

或者trim()之前打电话matches

extractedStr.trim().matches("^[A-Z0-9_-]+"); // true

PS:您也不需要_在字符类和连字符中转义(如果在开头或结尾使用)

于 2013-10-06T17:52:05.147 回答