Reputation: 749
Hi I want to match first name character by character but this make a error , this is my code:
int length = input.length();
for (int i = 0; i < length; i++){
char ch = input.charAt(i);
String regex ="^[_\\s]||[آ-ی]$";
Matcher matcher = Pattern.compile( regex ).matcher(ch);
and this is my complete code:
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
String input;
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edt);
button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ShowToast")
@Override
public void onClick(View v) {
input = editText.getText().toString();
check_reg();
}
});
}
public boolean check_reg(){
int length = input.length();
for (int i = 0; i < length; i++){
char ch = input.charAt(i);
String regex ="^[_\\s]||[آ-ی]$";
Matcher matcher = Pattern.compile( regex ).matcher(ch);
if (matcher.find( ))
{
result = matcher.group();
Toast.makeText(MainActivity.this, "match", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "no match", Toast.LENGTH_SHORT).show();
}
}
return false;
}
}
and this is a image of my problem:
Upvotes: 2
Views: 1759
Reputation: 12214
The compiler is telling you that you must pass a String
to the method matcher()
. You can not pass a char
to it.
You can create a String of length one if that is what you want.
You can use the regular expression in a more natural way and let it do the matching for you. For example:
public boolean check_reg(){
String regex ="^(?:[_\\s]||[آ-ی])+$";
Matcher matcher = Pattern.compile( regex ).matcher(input);
if (matcher.find( ))
{
result = matcher.group();
Toast.makeText(MainActivity.this, "match", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(MainActivity.this, "no match", Toast.LENGTH_SHORT).show();
return false;
}
}
This pattern will match, character-by-character, the entire input string.
Upvotes: 1
Reputation: 6360
The problem is that you are passing a char
type to the <Pattern>.matcher()
method, which only accepts types String
or CharSequence
. Here are the docs that explain it.
char ch = input.charAt(i);
String regex ="^[_\\s]||[آ-ی]$";
Matcher matcher = Pattern.compile( regex ).matcher(ch);
All you need to do to fix the error is to convert the char ch
variable to a string when you pass it to the matcher()
method.
char ch = input.charAt(i);
String regex ="^[_\\s]||[آ-ی]$";
Matcher matcher = Pattern.compile(regex).matcher(Character.toString(ch));
Upvotes: 1