RegEx
Links
Test tool for js: https://regex101.com/#javascript
For Ruby: http://rubular.com/
Debug regex: https://www.debuggex.com/
Usage
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
Checklist
Be careful about the greedy matching
.*
, try to add?
to use lazy matching:.*?
. See herePositive lookahead (does incldue):
(?=...)
Negative lookahead (not include multiple chars):
(?!...)
to match a single char that's not in the list, you can use
[^abc]
(means match one char that's not a or b or c)
Positive lookbehind:
(?<=...)
NOTE JavaScript doens't have this. You can use negative lookahead
Examples
How to replace "name" : "basic"
to "xxx" : "whatever you provided"
?
"name" : "basic"
to "xxx" : "whatever you provided"
?using grouping for everything: http://stackoverflow.com/a/6005637/166286
Find the number after a certain word:
The lookbehind assertion (?<=foo_bar) is important because you don't want to include %download%# in your results, only the numbers after it. http://stackoverflow.com/questions/4740984/c-sharp-regex-matches-example
How to make sure string 'po box' is not in the test string:
Use negative lookahead: /^(?!.*po\sBOX).*$/
How to find a pattern before a word:
Let's say we want to match and replace :user
in the url abc.com/:user/notebooks/:user-name/:userName
Use We could use: /:user(?=\b)/
, which will match the first :user
and :user-name
but not :userName
.
Split using a maximum length (Ruby)
Match string insdie single quotes
https://regex101.com/r/uH6uK3/1
match a word
use word boundary: \b
be sure to be lazy (+?)
Last updated