Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find if string has at least one character using regex?

Tags:

java

regex

Examples:

  1. "1 name": Should say it has characters
  2. "10,000": OK
  3. "na123me": Should say it has characters
  4. "na 123, 000": Should say it has characters
like image 405
Vishal Avatar asked May 20 '10 18:05

Vishal


People also ask

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do you check if a string has at least one letter and one number in Python?

Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method.

Which regex is used to match any single character?

A regular expression regexp followed by ? matches a string of one or zero occurrences of strings that matches regexp. In this expression (and the ones to follow), char is a regular expression that stands for a single character—for example, a literal character or a period ( . ).

What does ?= Mean in regular expression?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


1 Answers

public class HasCharacters  {
    public static void main( String [] args ){
        if( args[0].matches(".*[a-zA-Z]+.*")){
            System.out.println( "Has characters ");
        } else {
            System.out.println("Ok");   
        }
    }
}

Test

$java HasCharacters "1 name" 
Has characters 
$java HasCharacters "10,000"
Ok
$java HasCharacters "na123me"
Has characters 
$java HasCharacters "na 123, 000" 
Has characters 
like image 116
OscarRyz Avatar answered Sep 22 '22 00:09

OscarRyz