6

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.

viper
  • 1,836
  • 4
  • 25
  • 41
  • Maybe range of Unicode points `0xFF61 .. 0xFFDC`? – JosefZ Oct 30 '20 at 14:28
  • Okay so how would I do that? Please help me. – viper Oct 31 '20 at 04:50
  • `Pattern halfwidths = Pattern.compile("[\uFF61-\uFFDC]");` like in [this answer](https://stackoverflow.com/a/26838867/3439404) and a typical invocation sequence from [`java.util.regex.Pattern` official docs](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)? Could depend on _java_ version… – JosefZ Oct 31 '20 at 11:03
  • @JosefZ please explain to me further I cannot understand. I want the user entered string text to verify whether its half-width Japanese character or not – viper Nov 02 '20 at 03:49
  • @fr3ddie I am sorry sir I solved the problem I faced myself. And it seems 25+ has been already by the community to you. – viper Nov 11 '20 at 05:34

2 Answers2

2

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. ;)

fr3ddie
  • 406
  • 6
  • 17
0

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.
viper
  • 1,836
  • 4
  • 25
  • 41