user34537
user34537

Reputation:

Regex for /pattern/opt syntax?

How do i write a regex that matches the syntax in either perl ruby javascript

The syntax is like /my pattern here/modifiers where modifiers are i, g and other single letters.

I wrote the below however that wouldn't allow me to escape escape / with using . AFAIK i can write /Test\/Pattern/i in those languages to match the text Test/Pattern

/[^/]+/[^ ]*

Upvotes: 0

Views: 194

Answers (1)

Gumbo
Gumbo

Reputation: 655707

You need to take into account that the / might occur in the regular expression. But there is must be escaped. So:

/([^\\/]|\\.)*/[^ ]*

Here ([^\\/]|\\.) matches either any character except \ and / or an escaped character.

Furthermore, you often don’t need to escape the / if it’s inside a character class, so:

/([^\\/[]|\\.|\[([^\\\]]|\\.)*])*/[^ ]*

Here \[([^\\\]]|\\.)*] matches a literal [ followed by zero or more either any character except \ and ] or an escape sequence, followed by the literal ].

Additionally, modifiers are only alphabetic characters:

/([^\\/[]|\\.|\[([^\\\]]|\\.)*])*/[a-zA-Z]*

Upvotes: 2

Related Questions