I want to write a regex to test if a string contains ]][[. For ex:[[t]][[t]].
I am able to find a string which ends with ]] using the pattern:
RegExp(/]]/)
But if i try to use the pattern:
RegExp(/]\]\(?=\[\[)/)
for testing [[t]][[t]], the console displays the following error:
Uncaught Syntax Error: Invalid regular expression: /]\]\(?=\[\[)/: Unmatched ')'
Why you have a syntax error:
You are escaping ( with \(, so you get the Unmatched ')' error in \(?=\[\[).
How to fix it:
The best way to do this depends on exactly what you want.
If you just want to check that the string contains ]][[, don't use a regex:
if (yourString.indexOf(']][[') !== -1) {
// do something
}
If you really want to use a regex, you need to escape [s but not ]s:
if (/]]\[\[/.test(yourString)) {
// do something
}
If you really want to use a regex and not capture the [[:
if (/]](?=\[\[)/.test(yourString)) {
// do something
}
If you want to check for matching [[ and ]] (like [[t]]):
if (/\[\[[^[\]]*]]/.test(yourString)) {
// do something
}
If you want to check for two [[..]] strings back-to-back:
if (/(\[\[[^[\]]*]]){2}/.test(yourString)) {
// do something
}
If you want to check for one [[..]] string, followed by exactly the same string ([[t]][[t]] but not [[foo]][[bar]]):
if (/(\[\[[^[\]]*]])\1/.test(yourString)) {
// do something
}
Here's a demo of all of the above, along with a bunch of unit tests to demonstrate how each of these works.
Use this:
if (/]]\[\[/.test(yourString)) {
// It matches!
} else {
// Nah, no match...
}
Note that we need to escape the two opening braces with \[, but the closing braces ] do not need escaping as there is no potential confusion with a character class.
You need to escape the opening square brackets because it has a special meaning in regex which represents the start of a character class.
]](?=\[\[)
Try this one, this regex must match everything you need:
(\w*[\[\]]+\w*)+
But if for every open bracket [ there must be a closed bracket ], that's different.
What exactly you want?
Related
Let's assume I have an string... I want to convert them to numbers.. and It will only work for alphabets...
if my string contains comma or dot... I would like to avoid it...
I'm working with words by word. so if the string is--
"Hi, let's play!"
it should be converted to--
"4510, 584578'52 69775246!"
how can I do it?
function hasNumber(gottenWord) {
return (/\d/.test(gottenWord));
}
const numberTrue = hasNumber(gottenWord);
I was able to search for numbers but not sure how to search for symbols.. and I even have some custom symbols to search.
If all you want is to avoid anything that's not in abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ then the easiest way is to change \d to [^a-zA-Z]. [] indicates a character set, and starting a set with ^ means "not these".
I have a string in which I need to get the value between either "[ValueToBeFetched]" or "{ValueToBeFetched}".
var test = "I am \"{now}\" doing \"[well]\"";
test.match(/"\[.*?]\"/g)
the above regex serves the purpose and gets the value between square brackets and I can use the same for curly brackets also.
test.match(/"\{.*?}\"/g)
Is there a way to keep only one regex and do this, something like an or {|[ operator in regex.
I tried some scenarios but they don't seem to work.
Thanks in advance.
You could try following regex:
(?:{|\[).*?(?:}|\])
Details:
(?:{|\[): Non-capturing group, gets character { or [
.*?: gets as few as possible
(?:}|\]): Non-capturing group, gets character } or ]
Demo
Code in JavaScript:
var test = "I am \"{now}\" doing \"[well]\"";
var result = test.match(/"(?:{|\[).*?(?:}|\])"/g);
console.log(result);
Result:
["{now}", "[well]"]
As you said, there is an or operator which is |:
[Edited as suggested] Let's catch all sentences that begins with an "a" or a "b" :
/^((a|b).*)/gm
In this example, if the line parsed begins with a or b, the entire sentence will be catched in the first result group.
You may test your regex with an online regex tester
For your special case, try something like that, and use the online regex tester i mentionned before to understand how it works:
((\[|\{)\w*(\]|\}))
I am implementing a searching technique by autosuggest and solr.
I am getting a bunch of matching strings with special characters. For example, if I search for
jp
The returned strings include:
jp,
j p ,
j.p.,
j.p. nag,
j-p-naga
I need to highlight all strings contains "jp" by ignoring special characters.
expected output like :
"j-p-naga"---- "j-p" should highlight({span}j-p{/span}-naga
You want to eliminate special characters? Use regular expressions:
function removeSpecials(str) {
return str.replace(/[^a-zA-Z0-9]/g, '');
}
console.log('jp' === removeSpecials('j .$##p##'));
console.log('jp' === removeSpecials('j.p.,');
// Both true
Or maybe you want to check if a string contains the character j followed by p in any location?
function strHasJP(str) { return /[^j]*j[^p]*p.*/.test(str); }
I'm not sure what you are trying to do. For help on RegExp, go here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions .
I wrote this regexp to capture the strings below.
\!\[(.*?)?\]
All the strings below should match and return an optional string that's inside the first set of square brackets.
![]
![caption]
![]()
![caption]()
![caption][]
The problem is that this string also matches and returns ][ because the regex thinks it's between the first [ and last ].
![][] // Should not match, but does and returns "]["
How do I fix this?
Just remove the ? outside (.*?), that is redundant.
var myArray = ["![abc]","![caption]", "![def]()", "![caption]()","![caption][]"];
myArray.forEach(function(current) {
console.log(/!\[(.*?)\]/.exec(current)[1]);
});
Output
abc
caption
def
caption
caption
Check how the RegEx works here
Use this regex:
\!\[([^\]]*)\]
It means that it expects a "last" ] but makes internal ones invalid.
This should solve your issue.
My preference is this if you want to ignore catching the things like this ![[]]
\!\[([^\[\]]*)\]
i tried to do not show "SPAM" in string below using that regex:
alert("{SPAM\nSPAM} _1_ {SPAM} _2_".replace(/{[\s\S]+}/gm, ""));
What i was supposed to see was "~1~ ~2~"
(or something like that) but i got just ~2~. Why?
} and { are also elements of the character class [\s\S]. You should avoid matching this by:
/{[^}]+}/g
so that the regex stops once the } is found.