0

My code

    Scanner reader = new Scanner(System.in);
    String input = reader.nextLine();

    Pattern regex = Pattern.compile("^(<[a-z][0-9]>)|(<[\\/][a-z][0-9]>)");
    Matcher m = regex.matcher(input);

    while (m.find()) {
        listOfTags[i] = m.group();
        i++;
    }
    checkOpeningTag = listOfTags[0];
    checkClosingTag = listOfTags[1];
    for(int k = 0;k<listOfTags.length;k++){
        System.out.println("["+k+"] = "+listOfTags[k]);
    }

When I try to input <h1></h1> the output is

[0] = <h1>
[1] = </h1>

But when I input <h1><h1> the output is

[0] = <h1>
[1] = null

Why is it storing null value?

luk2302
  • 55,258
  • 23
  • 97
  • 137
Yupyep
  • 21
  • 2

2 Answers2

0

to make sure you aren't exceeding the length of your listOfTags you might want to do this:

if(listOfTags.length >= 2){
    checkOpeningTag = listOfTags[0];
    checkClosingTag = listOfTags[1];
}

to prevent storing nulls in your list:

int i = 0;
while(m.find()){
    if(m.group() != null){
        listOfTags[i] = m.group();
        i++;
    }
}
FrankK
  • 482
  • 8
  • 23
0

The ^ caret symbol in the current regex matches the start of string. So, the only opening tag that will get matched will be at the beginning of the string.

Remove the caret:

(<[a-z][0-9]>)|(</[a-z][0-9]>)

Or even merge the alternatives into if you do not need to differentiate between opening and closing tags:

</?[a-z][0-9]>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563