下面列出了怎么用android.util.Patterns的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Retrieves the user profile information in a manner supported by
* Gingerbread devices.
*
* @param context the context from which to retrieve the user's email address
* and name
* @return a list of the possible user's email address and name
*/
private static UserProfile getUserProfileOnGingerbreadDevice(Context context) {
// Other that using Patterns (API level 8) this works on devices down to
// API level 5
final Matcher valid_email_address = Patterns.EMAIL_ADDRESS.matcher("");
final Account[] accounts = AccountManager.get(context).getAccountsByType(GoogleAuthUtil
.GOOGLE_ACCOUNT_TYPE);
UserProfile user_profile = new UserProfile();
// As far as I can tell, there is no way to get the real name or phone
// number from the Google account
for (Account account : accounts) {
if (valid_email_address.reset(account.name).matches())
user_profile.addPossibleEmail(account.name);
}
// Gets the phone number of the device is the device has one
if (context.getPackageManager().hasSystemFeature(Context.TELEPHONY_SERVICE)) {
final TelephonyManager telephony = (TelephonyManager) context.getSystemService
(Context.TELEPHONY_SERVICE);
user_profile.addPossiblePhoneNumber(telephony.getLine1Number());
}
return user_profile;
}
@Bindable
public String getEmail() {
if (email == null) {
return "";
} else if (Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Log.d(TAG, "getEmail: " + getCustomerId());
DataBaseController.getInstanse().checkEmailExist(getContext(), email, new DataBaseCallBack() {
@Override
public void onSuccess(Object responseData, String successMsg) {
if (((Customer) responseData) != null && ((Customer) responseData).getCustomerId() != getCustomerId()) {
isEmailExist = true;
} else {
isEmailExist = false;
}
Log.d(TAG, "onSuccess: " + responseData);
}
@Override
public void onFailure(int errorCode, String errorMsg) {
isEmailExist = false;
}
});
}
return email;
}
public boolean isValid() {
if (TextUtils.isEmpty(username)) {
return false;
}
if (!Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
return false;
}
if (TextUtils.isEmpty(password)) {
return false;
}
if (password.length() < 5) {
return false;
}
return true;
}
private boolean hasError(LoginCredentials loginCredentials) {
String username = loginCredentials.getUsername();
String password = loginCredentials.getPassword();
if (TextUtils.isEmpty(username)) {
loginListener.onFailed("The email is empty");
return true;
}
if (!Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
loginListener.onFailed("The email is invalid");
return true;
}
if (TextUtils.isEmpty(password)) {
loginListener.onFailed("The password is empty");
return true;
}
if (password.length() < 5) {
loginListener.onFailed("Password is weak");
return true;
}
return false;
}
static Credential parseCredential(String cred) {
final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
final String country = Locale.getDefault().getCountry();
if (Patterns.PHONE.matcher(cred).matches()) {
// Looks like a phone number.
try {
// Normalize phone number format
cred = phoneUtil.format(phoneUtil.parse(cred, country), PhoneNumberUtil.PhoneNumberFormat.E164);
// Exception not thrown, we have a phone number.
return new Credential(Credential.METH_PHONE, cred);
} catch (NumberParseException ignored) {
return null;
}
}
// Not a phone number. Try parsing as email.
if (Patterns.EMAIL_ADDRESS.matcher(cred).matches()) {
return new Credential(Credential.METH_EMAIL, cred);
}
return null;
}
@Override
protected void onResume() {
super.onResume();
Core core = LinphoneManager.getCore();
if (core != null) {
reloadLinphoneAccountCreatorConfig();
}
getAccountCreator().addListener(mListener);
if (getResources().getBoolean(R.bool.pre_fill_email_in_assistant)) {
Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
for (Account account : accounts) {
if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
String possibleEmail = account.name;
mEmail.setText(possibleEmail);
break;
}
}
}
}
private static void linkifyText(final String text, final StringBuffer outputBuffer) {
String prepared = replaceAll(text, BITCOIN_URI_PATTERN, "<a href=\"$0\">$0</a>");
Matcher m = Patterns.WEB_URL.matcher(prepared);
while (m.find()) {
int start = m.start();
if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
if (m.group().indexOf(':') > 0) { // With no URI-schema we may get "http:/" links with the second / missing
m.appendReplacement(outputBuffer, "<a href=\"$0\">$0</a>");
} else {
m.appendReplacement(outputBuffer, "<a href=\"http://$0\">$0</a>");
}
} else {
m.appendReplacement(outputBuffer, "$0");
}
}
m.appendTail(outputBuffer);
}
@Override
public boolean enableBlocker() {
//contentBlocker56.setUrlBlockLimit(15_000);
if (contentBlocker56.enableBlocker()) {
SharedPreferences sharedPreferences = App.get().getApplicationContext().getSharedPreferences("dnsAddresses", Context.MODE_PRIVATE);
if (sharedPreferences.contains("dns1") && sharedPreferences.contains("dns2")) {
String dns1 = sharedPreferences.getString("dns1", null);
String dns2 = sharedPreferences.getString("dns2", null);
if (dns1 != null && dns2 != null
&& Patterns.IP_ADDRESS.matcher(dns1).matches()
&& Patterns.IP_ADDRESS.matcher(dns2).matches()) {
this.setDns(dns1, dns2);
}
Log.d(TAG, "Previous dns addresses has been applied. " + dns1 + " " + dns2);
}
return true;
}
return false;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
ClipboardManager cm = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
ClipData clipData = cm.getPrimaryClip();
if (clipData == null) {
return;
}
int count = clipData.getItemCount();
for (int i = 0; i < count; i++) {
ClipData.Item item = clipData.getItemAt(i);
CharSequence text = item.getText();
if (text != null && text.length() > 0) {
if (Patterns.WEB_URL.matcher(text).find()) {
Log.d(TAG, "Text contains web url, not pasting: " + text);
return;
}
viewPager.setCurrentItem(0);
cm.setPrimaryClip(ClipData.newPlainText(null, ""));
appSectionsPagerAdapter.tabLookup.setQuery(text.toString());
break;
}
}
}
public AndroidShareDialog(Context context, int theme, String msgText, final String imgUri) {
super(context, theme);
this.msgText = msgText;
if(TextUtils.isEmpty(imgUri)){
this.mImgPath = null;// getAppLauncherPath();
}else{
if (Patterns.WEB_URL.matcher(imgUri).matches()) {
new Thread(new Runnable() {
public void run() {
try {
mImgPath = getImagePath(imgUri, getFileCache());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} else {
this.mImgPath = imgUri;
}
}
}
private ArrayList<String> getUserEmail(){
ArrayList<String> email = new ArrayList<String>();
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(VerifyOTP.this).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
if(possibleEmail != null)
if(possibleEmail.length() !=0 ){
email.add(possibleEmail);
}
}
}
return email;
}
private ArrayList<String> getUserEmail(){
ArrayList<String> email = new ArrayList<String>();
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(VerifyOTP.this).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
if(possibleEmail != null)
if(possibleEmail.length() !=0 ){
email.add(possibleEmail);
}
}
}
return email;
}
@Override
protected View inflateView(ViewGroup parentView) {
if (context != null) {
getValidationEngine()
.addEmailValidation(new RegexValidation(Patterns.EMAIL_ADDRESS.pattern(),
context.getString(
R.string.invalid_email)));
}
View signUpView = LayoutInflater.from(context)
.inflate(R.layout.signup_email, parentView, false);
usernameEt = (EditText) signUpView.findViewById(R.id.username);
emailEt = (EditText) signUpView.findViewById(R.id.email);
passwordEt = (EditText) signUpView.findViewById(R.id.password);
welcomeTv = (TextView) signUpView.findViewById(R.id.tv_welcome_text);
theme = Argus.getInstance().getArgusTheme();
themeHelper.applyTheme(signUpView, theme);
return signUpView;
}
@SuppressLint("NewApi")
private void setupAccountAutocomplete() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) ==
PackageManager.PERMISSION_GRANTED) {
permissionPrimer.setVisibility(View.GONE);
final Account[] accounts = AccountManager.get(this).getAccounts();
final Set<String> emailSet = new HashSet<>();
for (Account account : accounts) {
if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
emailSet.add(account.name);
}
}
username.setAdapter(new ArrayAdapter<>(this,
R.layout.account_dropdown_item, new ArrayList<>(emailSet)));
} else {
if (shouldShowRequestPermissionRationale(Manifest.permission.GET_ACCOUNTS)) {
setupPermissionPrimer();
} else {
permissionPrimer.setVisibility(View.GONE);
shouldPromptForPermission = true;
}
}
}
/**
* Extract urls from string.
* @param input
* @return
*/
public static List<String> extractUrls(String input)
{
List<String> result = new ArrayList<String>();
String[] words = input.split("\\s+");
Pattern pattern = Patterns.WEB_URL;
for(String word : words)
{
if(pattern.matcher(word).find())
{
if(!word.toLowerCase().contains("http://") && !word.toLowerCase().contains("https://"))
{
word = "http://" + word;
}
result.add(word);
}
}
return result;
}
private static void linkifyText(final String text, final StringBuffer outputBuffer) {
String prepared = replaceAll(text, BITCOIN_URI_PATTERN, "<a href=\"$0\">$0</a>");
Matcher m = Patterns.WEB_URL.matcher(prepared);
while (m.find()) {
int start = m.start();
if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
if (m.group().indexOf(':') > 0) { // With no URI-schema we may get "http:/" links with the second / missing
m.appendReplacement(outputBuffer, "<a href=\"$0\">$0</a>");
} else {
m.appendReplacement(outputBuffer, "<a href=\"http://$0\">$0</a>");
}
} else {
m.appendReplacement(outputBuffer, "$0");
}
}
m.appendTail(outputBuffer);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
final String linkText = getLinkText(tex, spannable, event);
LinkType linkType = LinkType.NONE;
if (Patterns.PHONE.matcher(linkText).matches()) {
linkType = LinkType.PHONE;
} else if (Patterns.WEB_URL.matcher(linkText).matches()) {
linkType = LinkType.WEB_URL;
} else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
linkType = LinkType.EMAIL_ADDRESS;
}
if (listener != null) {
listener.onLinkClicked(linkText, linkType);
}
return false;
}
public static Type getType(String url) {
if (url == null) return Type.INVALID;
if (!URLUtil.isValidUrl(url)) {
if (Patterns.EMAIL_ADDRESS.matcher(url).matches()) {
return Type.EMAIL;
}
return Type.INVALID;
}
if (url.contains("behance.")) {
return Type.BEHANCE;
} else if (url.contains("dribbble.")) {
return Type.DRIBBBLE;
} else if (url.contains("facebook.")) {
return Type.FACEBOOK;
} else if (url.contains("github.")) {
return Type.GITHUB;
} else if (url.contains("instagram.")) {
return Type.INSTAGRAM;
} else if (url.contains("pinterest.")) {
return Type.PINTEREST;
} else if (url.contains("twitter.")) {
return Type.TWITTER;
} else if (url.contains("t.me/") || url.contains("telegram.me/")) {
return Type.TELEGRAM;
} else {
return Type.UNKNOWN;
}
}
protected Intent parseIntent(XmlResourceParser parser) {
final String url = getAttributeValue(parser, ATTR_URL);
if (TextUtils.isEmpty(url) || !Patterns.WEB_URL.matcher(url).matches()) {
if (LOGD) Log.d(TAG, "Ignoring shortcut, invalid url: " + url);
return null;
}
return new Intent(Intent.ACTION_VIEW, null).setData(Uri.parse(url));
}
/**
* Attempts to determine whether user input is a URL or search
* terms. Anything with a space is passed to search if canBeSearch is true.
* <p/>
* Converts to lowercase any mistakenly uppercased schema (i.e.,
* "Http://" converts to "http://"
*
* @param canBeSearch If true, will return a search url if it isn't a valid
* URL. If false, invalid URLs will return null
* @return Original or modified URL
*/
@NonNull
public static String smartUrlFilter(@NonNull String url, boolean canBeSearch, String searchUrl) {
String inUrl = url.trim();
boolean hasSpace = inUrl.indexOf(' ') != -1;
Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
if (matcher.matches()) {
// force scheme to lowercase
String scheme = matcher.group(1);
String lcScheme = scheme.toLowerCase();
if (!lcScheme.equals(scheme)) {
inUrl = lcScheme + matcher.group(2);
}
if (hasSpace && Patterns.WEB_URL.matcher(inUrl).matches()) {
inUrl = inUrl.replace(" ", "%20");
}
return inUrl;
}
if (!hasSpace) {
if (Patterns.WEB_URL.matcher(inUrl).matches()) {
return URLUtil.guessUrl(inUrl);
}
}
if (canBeSearch) {
return URLUtil.composeSearchUrl(inUrl,
searchUrl, QUERY_PLACE_HOLDER);
}
return "";
}
private boolean isInputValid() {
boolean isValid = true;
if (mPassword.length() == 0) {
isValid = false;
mPassword.setError(getString(R.string.password_required));
}
if (mUserName.length() == 0) {
isValid = false;
mUserName.setError(getString(R.string.username_required));
}
if (mServerEditText.length() == 0) {
isValid = false;
mServerEditText.setError(getString(R.string.server_domain_required));
} else {
String serverString = mServerEditText.getText().toString();
if (!serverString.contains("://")) {
serverString = "https://" + serverString;
}
if (!Patterns.WEB_URL.matcher(serverString).matches()) {
mServerEditText.setError(getString(R.string.invalid_domain));
isValid = false;
}
}
return isValid;
}
private String findUrlInText(String text) {
List<String> urls = new ArrayList<>();
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
String url = m.group();
urls.add(url);
}
if (urls.size() > 0) {
return urls.get(0);
}
return null;
}
@Override
protected void onStop() {
super.onStop();
final String urlString = endpointEditText.getText().toString();
if (Patterns.WEB_URL.matcher(urlString).matches()) {
SharedPreferences preferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
preferences.edit()
.putString(LinkAPIClient.SHARELOCK_ENDPOINT_KEY, urlString)
.apply();
}
}
private boolean isUrlValid(String url) {
if (BuildConfig.DEBUG) {
return Patterns.WEB_URL.matcher(String.valueOf(url)).matches() ||
Patterns.IP_ADDRESS.matcher(url).matches();
} else {
return Patterns.WEB_URL.matcher(String.valueOf(url)).matches();
}
}
/**
* Triggers a send email intent. If no application has registered to receive these intents,
* this will fail silently.
*
* @param context The context for issuing the intent.
* @param email The email address to send to.
* @param subject The subject of the email.
* @param body The body of the email.
* @param chooserTitle The title of the activity chooser.
* @param fileToAttach The file name of the attachment.
*/
@CalledByNative
static void sendEmail(Context context, String email, String subject, String body,
String chooserTitle, String fileToAttach) {
Set<String> possibleEmails = new HashSet<String>();
if (!TextUtils.isEmpty(email)) {
possibleEmails.add(email);
} else {
Pattern emailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
possibleEmails.add(account.name);
}
}
}
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("message/rfc822");
if (possibleEmails.size() != 0) {
send.putExtra(Intent.EXTRA_EMAIL,
possibleEmails.toArray(new String[possibleEmails.size()]));
}
send.putExtra(Intent.EXTRA_SUBJECT, subject);
send.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(body));
if (!TextUtils.isEmpty(fileToAttach)) {
File fileIn = new File(fileToAttach);
send.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileIn));
}
try {
Intent chooser = Intent.createChooser(send, chooserTitle);
// we start this activity outside the main activity.
chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(chooser);
} catch (android.content.ActivityNotFoundException ex) {
// If no app handles it, do nothing.
}
}
private boolean isValid(String urlString) {
try {
URL url = new URL(urlString);
return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
} catch (MalformedURLException e) {
}
return false;
}
public void connect() {
String text = textBox.getText().toString();
if (Patterns.WEB_URL.matcher(text).matches()) {
if (!text.startsWith("http")) {
text = "http://" + text;
}
activity.getBrowserManager().newWindow(text);
} else {
text = "https://google.com/search?q=" + text;
activity.getBrowserManager().newWindow(text);
}
}
/**
* Returns true if the given string is an email.
*/
private static boolean isEmail(String account) {
if (TextUtils.isEmpty(account)) {
return false;
}
final Pattern emailPattern = Patterns.EMAIL_ADDRESS;
final Matcher matcher = emailPattern.matcher(account);
return matcher.matches();
}
@Override
public void bind(Checkin checkin, ImageLoader imageLoader) {
mName.setText(checkin.getAttendeeName());
Context context = mDescription.getContext();
long timestamp = checkin.getTimestamp();
if (System.currentTimeMillis() - timestamp * 1000 < 60 * 1000) {
mDescription.setText(R.string.just_now);
} else {
mDescription.setText(
DateUtils.getRelativeDateTimeString(context, timestamp * 1000,
DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0));
}
// Load the icon
ImageLoader.ImageContainer container = (ImageLoader.ImageContainer) mIcon.getTag();
if (container != null) {
container.cancelRequest();
}
String imageUrl = checkin.getAttendeeImageUrl();
if (!TextUtils.isEmpty(imageUrl) && Patterns.WEB_URL.matcher(imageUrl).matches()) {
mIcon.setTag(imageLoader.get(imageUrl,
new RoundedImageListener(mIcon, R.drawable.ic_person,
R.drawable.ic_person)));
} else {
mIcon.setImageResource(R.drawable.ic_person);
}
if (mWillAnimate && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mCheckin.setImageResource(R.drawable.checkin_anim);
} else {
mCheckin.setImageResource(R.drawable.checkin);
}
}
InetAddress getDirectInetAddress() throws IOException {
if (mTarget != null) {
final String hn = mTarget.getHostName();
if (hn != null && Patterns.IP_ADDRESS.matcher(hn).matches())
return InetAddress.getByName(hn);
}
throw new IOException();
}