Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this `/^.*$/` regex match?

I'm maintaining some old code when I reached a headscratcher. I am confused by this regex pattern: /^.*$/ (as supplied as an argument in textFieldValidation(this,'true',/^.*$/,'','').

I interpret this regex as:

  • /^=open pattern
  • .=match a single character of any value (Except EOL)
  • *=match 0 or more times
  • $=match end of the line
  • /=close pattern

So…I think this pattern matches everything, which means the function does nothing but waste processing cycles. Am I correct?

like image 351
Jeromy French Avatar asked May 09 '13 19:05

Jeromy French


People also ask

What does * do in regex?

The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.

What is the meaning of * in regex?

. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.

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. 1* means any number of ones.

What does this regex mean a zA Z0 9 *?

The bracketed characters [a-zA-Z0-9] mean that any letter (regardless of case) or digit will match. The * (asterisk) following the brackets indicates that the bracketed characters occur 0 or more times.


3 Answers

It matches a single line of text.

It will fail to match a multiline String, because ^ matches the begining of input, and $ matches the end of input. If there are any new line (\n) or caret return (\r) symbols in between - it fails.

For example, 'foo'.match(/^.*$/) returns foo.

But 'foo\nfoo'.match(/^.*$/) returns null.

like image 134
Oleg Mikheev Avatar answered Sep 23 '22 06:09

Oleg Mikheev


^ "Starting at the beginning."
. "Matching anything..."
* "0 or more times"
$ "To the end of the line."

Yep, you're right on, that matches empty or something.

And a handy little cheat sheet.

like image 28
dougBTV Avatar answered Sep 22 '22 06:09

dougBTV


The regexp checks that the string doesn't contain any \n or \r. Dots do not match new-lines.

Examples:

/^.*$/.test("");  // => true
/^.*$/.test("aoeu");  // => true
/^.*$/.test("aoeu\n");  // => false
/^.*$/.test("\n");  // => false
/^.*$/.test("aoeu\nfoo");  // => false
/^.*$/.test("\nfoo");  // => false
like image 37
Florian Loitsch Avatar answered Sep 26 '22 06:09

Florian Loitsch