trouble with writing regex java -


string consists of 2 distinct alternating characters. example, if string 's 2 distinct characters x , y, t xyxyx or yxyxy not xxyy or xyyx.

but a.matches() returns false , output becomes 0. me understand what's wrong here.

public static int check(string a) {     char on = a.charat(0);     char = a.charat(1);     if(on != to) {         if(a.matches("["+on+"("+to+""+on+")*]|["+to+"("+on+""+to+")*]"))  {              return a.length();         }                 }     return 0; } 

use regex (.)(.)(?:\1\2)*\1?.

  • (.) match character, , capture group 1
  • (.) match character, , capture group 2
  • \1 match same characters captured in group 1
  • \2 match same characters captured in group 2
  • (?:\1\2)* match 0 or more pairs of group 1+2
  • \1? optionally match dangling group 1

input must @ least 2 characters long. empty string , one-character string not match.

as java code, be:

if (a.matches("(.)(.)(?:\\1\\2)*\\1?")) { 

see regex101.com working examples1.

1) note regex101 requires use of ^ , $, implied matches() method. requires use of flags g , m showcase multiple examples @ same time.


update

as pointed out austin anderson:

fails on yyyyyyyyy or xxxxxx

to prevent that, can add zero-width negative lookahead, ensure input doesn't start 2 of same character:

(?!(.)\1)(.)(.)(?:\2\3)*\2?

see regex101.com.

or can use austin anderson's simpler version:

(.)(?!\1)(.)(?:\1\2)*\1?


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -