Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose any symbol in javascript regex

I have a string containing something like this

"... /\*start  anythingCanBeEnteredHere   end\*/  ..."

I need a regex that gets only the anythingCanBeEnteredHere part, which can be a collection of any number of symbols.

The problem is that I can't find any shortcut/flag that will choose any symbol

So far I use this regex

var regex = /start([^\~]*)end/; 
var templateCode = myString.match(regex);

[^\~] chooses any symbol except "~" (which is a hack) and works fine, but I really need all symbols.

I've also tried this [^] but it doesn't work right.

like image 345
Olga Avatar asked Jan 20 '12 11:01

Olga


People also ask

How do I match a specific character in regex?

Match any specific character in a set Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.

How do I allow special characters in JavaScript?

/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges. /a-zA-Z0-9/ does mean the literal sequence of those 9 characters. Which chars from .!

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


3 Answers

 /start(.*)end/

will match FOO in startFOOend and BARendBAZ in startBARendBAZend.

 /start(.*?)end/

will match FOO in startFOOend and BAR in startBARendBAZend.

The dot matches anything except a newline symbol (\n). If you want to capture newlines as well, replace dot with [\s\S]. Also, if you don't allow the match to be empty (as in startend), use + instead of *.

See http://www.regular-expressions.info/reference.html for more info.

like image 152
georg Avatar answered Oct 24 '22 13:10

georg


I'm not sure I understand what you mean by "symbol", if you mean anything, that's what the dot . will match

Are you trying to do this?

var regex = /start(.*)end/; 
var templateCode = myString.match(regex);
like image 37
Sam Greenhalgh Avatar answered Oct 24 '22 14:10

Sam Greenhalgh


To match any character, you should not use the dot operator (.) because it does not match line breaks. To include line breaks, use .|[\r\n] (character or line break) or [\s\S] (space or non-space characters).

var regex = /start[\s\S]*end/;
var templateCode = myString.match(regex);
like image 20
yaya Avatar answered Oct 24 '22 14:10

yaya