Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for ONE-or-more letters/digits And ZERO-or-more spaces

Tags:

java

regex

I want to allow 0 or more white spaces in my string and one or more A-Z or a-z or 0-9 in my string.

Regex allowing a space character in Java

suggests [0-9A-Za-z ]+.

I doubt that, this regex matches patterns having zero or more white spaces.

What to do to allow 0 or more whitespaces anywhere in the string and one or more characters anywhere in the string.

Will this work? ([0-9A-Za-z]+)([ ]*)

like image 285
vplusplus Avatar asked Apr 15 '14 18:04

vplusplus


People also ask

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

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

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


4 Answers

I believe you can do something like this:

([ ]*+[0-9A-Za-z]++[ ]*+)+

This is 0 or more spaces, followed by at least 1 alphanum char, followed by 0 or more spaces

^^ that whole thing at least once.

Using Pshemo's idea of possessive quantifiers to speed up the regex.

like image 187
Cruncher Avatar answered Oct 22 '22 10:10

Cruncher


The most simple answer

* means zero or more equivalent to {0,}

+ means one or more equivalent to {1,}

so look at this

[A-Z]+ means at least one Capital Letter, can be written as [A-Z]{1,}

[!@#$%&]. means you can have these Special Characters zero or more times can be written as [!@#$%&]{0,}

sorry but

the purpose of this answer to be as Simple as possible

like image 12
Basheer AL-MOMANI Avatar answered Oct 22 '22 08:10

Basheer AL-MOMANI


You can try also this :

  ^[0-9A-Za-z ]*[0-9A-Za-z]+[ ]*$
like image 7
donut Avatar answered Oct 22 '22 10:10

donut


Use lookahead:

^(?=.*\s*)(?=.*[a-zA-Z0-9]+)[a-zA-Z0-9 ]+$
like image 4
Toto Avatar answered Oct 22 '22 08:10

Toto