2017-02-15 35 views
2

喜不工作,我想通過字符匹配名字字符,但這個做一個錯誤,這是我的代碼:正則表達式的Android

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

,這是我的完整代碼:

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; 
    } 
} 

,這是我的問題的一個形象:

enter image description here

+0

我猜它的Java的東西? –

+0

從我在[docs](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)中讀到的內容中,'pattern.matcher()'方法只接受'String'和'CharSequence'類型...不是'char' –

+0

爲什麼要按字符檢查字符?你可以使用'^ [_ \ sā-ı] + $'來檢查它作爲一個整個字符串。 'input.matches(「[_ \ sā-ı] +」)' –

回答

1

問題是您將char類型傳遞給<Pattern>.matcher()方法,該方法只接受StringCharSequence的類型。 Here are the docs that explain it.

char ch = input.charAt(i); 
String regex ="^[_\\s]||[آ-ی]$"; 
Matcher matcher = Pattern.compile(regex).matcher(ch); 

所有你需要做什麼來修復該錯誤是,當你把它傳遞給matcher()方法到char ch變量轉換爲字符串。

char ch = input.charAt(i); 
String regex ="^[_\\s]||[آ-ی]$"; 
Matcher matcher = Pattern.compile(regex).matcher(Character.toString(ch)); 
1

編譯器告訴你,你必須通過String的方法matcher()。您無法將char傳遞給它。

如果這是你想要的,你可以創建一個長度爲1的字符串。

您可以以更自然的方式使用正則表達式,並讓它爲您進行匹配。例如:

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; 
     } 
} 

此模式會匹配,字符逐字符,整個輸入串。