判断java标识符

coding

 1package com.jdk7.chapter5;

2

3publicclass JavaIdentifier {

4

5/**

6 * 使用Character.isJavaIdentifierPart判断字符是否属于java标识符

7 it is a letter

8 it is a currency symbol (such as '$')

9 it is a connecting punctuation character (such as '_')

10 it is a digit

11 it is a numeric letter (such as a Roman numeral character)

12 it is a combining mark

13 it is a non-spacing mark

14 '\u005Cu0000' through '\u005Cu0008'

15 '\u005Cu000E' through '\u005Cu001B'

16 '\u005Cu007F' through '\u005Cu009F'

17 * @param str

18 * @return

19*/

20publicstaticboolean isJavaIdentifier(String str){

21if(str==null || str.length()==0){

22returnfalse;

23 }

24char[] ch = str.toCharArray();

25for(int i=0;i<ch.length;i++){

26if(!(Character.isJavaIdentifierPart(ch[i]))){

27returnfalse;

28 }

29 }

30returntrue;

31 }

32

33publicstaticvoid main(String[] args) {

34 System.out.println("my_var is an identifier? "+JavaIdentifier.isJavaIdentifier("my_var"));

35 System.out.println("$my_var is an identifier? "+JavaIdentifier.isJavaIdentifier("$my_var"));

36 System.out.println("my_var.1 is an identifier? "+JavaIdentifier.isJavaIdentifier("my_var.1"));

37 System.out.println("1$my_var is an identifier? "+JavaIdentifier.isJavaIdentifier("1$my_var"));

38 System.out.println("u0391var is an identifier? "+JavaIdentifier.isJavaIdentifier("u0391var"));

39 System.out.println("null is an identifier? "+JavaIdentifier.isJavaIdentifier(null));

40 System.out.println("null is an identifier? "+JavaIdentifier.isJavaIdentifier(" "));

41 }

42}

43

44

45执行结果:

46 my_var is an identifier? true

47 $my_var is an identifier? true

48 my_var.1 is an identifier? false

49 1$my_var is an identifier? true

50 u0391var is an identifier? true

51null is an identifier? false

52null is an identifier? false

以上是 判断java标识符 的全部内容, 来源链接: utcz.com/z/508946.html

回到顶部