Android : Validate half-width Japanese character

Viewed 915

This question might have been asked several times but I didn't find a proper answer so I am posting this question. What I want to do is validate the Japanese text entered in the edit text field to allow only half-width Japanese characters. I only want to check the validation once user enters the text and taps on some action button.

2 Answers

I've created method validates if typed character is half-width kana:

public boolean validate(String c) {
    Pattern pattern = Pattern.compile("[\uff61-\uff9f]");
    return pattern.matcher(c).matches();
}

I understood that you want to check is written text composed of only half-width kana, yes? To do this, in onClick() of button which you clicking for validate, write something like this:

for (int i = 0; i < textToValidate.length(); i++) {
    if (validate(textToValidate.charAt(i))) {
        continue;
    } else {
        System.out.println("Text wasn't written in half-width kana.");
        return;
    }
}
System.out.println("Text was written in half-width kana.");

Let me know if my answer is helpful for you. ;)

Okay so I came across many solutions and this one worked for me. Basically, I have a Japanese half-width validation regex and compared it to my string.

val halfWidthRegex = "^[ァ-ン゙゚]+\\s?[ァ-ン゙゚]+$"

if(myText?.matches(halfWidthRegex.toRegex()))
  // Valid halfwidth text
else // Invalid halfwidth text.
Related