验证手机号码的正则表达式
来源:互联网 发布:淘宝直通车关键词词典 编辑:程序博客网 时间:2024/05/08 03:37
转载自:http://blog.csdn.net/afanbaby/article/details/52173933
利用正则表达式来验证手机号是否合法,现在我们简单使用一下,这个在实际的应用中很实用。
例:在输入框中输入手机号,判断是否合法,
MainActivity中:
package com.example.mac.judgedemo;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btn; private EditText et; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btn); et = (EditText) findViewById(R.id.et); tv = (TextView) findViewById(R.id.tv); btn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn: String number = et.getText().toString(); boolean judge = isMobile(number); if (judge == true) { tv.setText("手机号合法"); } else { tv.setText("手机号不合法"); } break; } } /** * 验证手机格式 */ public static boolean isMobile(String number) { String num = "[1][358]\\d{9}"; if (TextUtils.isEmpty(number)) { return false; } else { return number.matches(num); } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
MainActivity的布局文件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="10dp" tools:context="com.example.mac.judgedemo.MainActivity"> <EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入手机号" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="判断" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="显示结果" /></LinearLayout>