簡體   English   中英

正則表達式表達式以檢查字母數字字符串不起作用

[英]Regex expression to check for alphanumeric string does not work

我正在嘗試測試我的String是否包含一個字符(az)(AZ)和一個數字(0-9)

package testing;

import java.io.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;


public class Testing extends JPanel 
{

    public static void main(String[] args) 
    {
        String foo = "abc1";

        if (foo.matches(".*[0-9].*") && foo.matches(".*[A-Z].*") && foo.matches(".*[a-z].*"))
        {
            //contain letters and numbers only
            System.out.println("Foo");
        }


    }


}

我期望Foo將被打印出來,但是我的正則表達式表達式似乎存在問題。 有人可以幫我嗎 ??

謝謝

更改

foo.matches(".*[0-9].*") && foo.matches(".*[A-Z].*") && foo.matches(".*[a-z].*")

foo.matches(".*[0-9].*") && (foo.matches(".*[A-Z].*") || foo.matches(".*[a-z].*"))

您的問題是foo.matches(".*[AZ].*")將返回false ,因為foo = "abc1"中沒有大寫字母。

foo.matches(".*([0-9]+).*") && foo.matches(".*([a-zA-Z]+).*")

下面將在一個正則表達式中標識一個匹配項:

foo.matches(".*([0-9].*[a-zA-Z])|([a-zA-Z].*[0-9]).*")

您可以使用單個表達式而不是多個表達式,如下所示:

if (foo.matches("(?=.*[a-zA-Z])(?=.*[0-9]).*")) {
    //...

這樣可以確保foo至少包含一個字母(小寫或大寫)和至少一個數字。

嘗試以下Alpha數值正則表達式...

foo.matches("\\w.*")

要么

foo.matches("\\w+");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM