-1

I was writing a regex expression to replace the string pattern with its own sub-string. And I don't really know if thats possible (I have only worked with regex once before).

Example:

Convert this:

ObjectId(shkijfn8bshhby302knw);

to

"shkijfn8bshhby302knw"

If its possible doing this, can someone please guide me to a guide or tutorial.

EDIT: Modified the question. Actually I wanted to add quotes to string taken from initial string.

Jehanzeb.Malik
  • 3,332
  • 4
  • 25
  • 41

2 Answers2

3

Using this replacement, you can extract the parameter value as you wish:

Of course, it all depends on what environment/language/IDE/text editor you are doing this with, but this should work for you.

(I just read your comment stating you're using JavaScript, and this regex is indeed compatible with JavaScript.)

Free spaced:

  • ObjectId\(": The literal string ObjectId(", which is discarded
  • (\w+): One or more word-characters, which are captured (that's what the $1 is for. It's the first capture group)
  • "\);: The literal string ");, which is discarded.

Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference.

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
0

This will work in most regex flavors:

Search: ObjectId\("([^"]*)"\);

Replace: $1

The parentheses in ([^"]*) capture any chars that are not a " to Group 1. This is your substring. We replace the entire match with Group 1.

zx81
  • 41,100
  • 9
  • 89
  • 105