This question already has answers here:
How to detect exact length in regex
(8 answers)
Closed 4 years ago.
So I am trying to use a regular expression to check against strings but it doesn't seem to be working properly.
Basically I want it to match a alpha-numeric string that is exactly 3 characters long. The expression I am using below does not seem to be working for this:
const msg = message.content;
const regex = /[A-Za-z0-9]{3}/g;
if (msg.match(regex)) {
// Do something
}
Am I doing something wrong? Any help would be appreciated. Thanks in advance.
You need to add ^ and $ for the start-of-string anchor and end-of-string anchor, respectively - otherwise, for example, for #123, the 123 will match, and it will pass the regex. You also might consider using the i flag rather than repeat A-Za-z, and you can use \d instead of 0-9.
It looks like you just want to check whether the string passes the regex's test or not, in which case .test (evaluates to a boolean) might be a bit more appropriate than .match. Also, either way, there's no need for the global flag if you're just checking whether a string passes a regex:
const regex = /^[a-z\d]{3}$/i;
if (regex.test(msg)) {
// do something
}
Related
This question already has answers here:
Regular expression to stop at first match
(9 answers)
Closed 7 months ago.
I am trying to perform this transformation to a string (using javascript):
Input:
[hello]{world}and[good]{night}
Output:
<span class="top">hello<span class="bottom">world</span></span>and<span class="top">good<span class="bottom">night</span></span>
To do that I am using the following regex:
text.replace(/\[(.*)\]\{(.*)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")
It works correctly when only setting one occurrence of the pattern in a string [hello]{world}
But if I add a string with more than one, the regex matches the first [] and the last {} instead, and prints this:
<span class='top'>hello]{world}and[good<span class='bottom'>night</span></span>
How can I tell regex to match the first pattern and the second pattern instead of matching it as one bigger pattern?
Note that between the [] and {} I expect there to be no text. So [hello]world and good{night} should not be matched.
You need to put ? after .* to make the quantifier lazy, instead of greedy.
const text = '[hello]{world}and[good]{night}'
const result = text.replace(/\[(.*?)\]\{(.*?)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")
console.log(result)
This question already has an answer here:
javascript regexp replace not working, but string replace works
(1 answer)
Closed 1 year ago.
Hello team I am new to JS so I am trying to use RegEx with replacing to take input from the user and replace it if it doesn't match the RegEx I have to be able to put 7 digits or 6 digits followed with one letter currently I am doing this
someID.replace('^(([0-9]{1,7})|([0-9]{1,6}[a-zA-Z]{1}))$')
I am not able to replace the current string with the RegEx expression if I enter
12345678900 it remain the same in that situation I need to be 1234567 after the replace or if I have 12345678asd to be 123456a. How can I achieve that by only replace function and a RegEx expresion
You need to use a different regex and a dirrent replace function.
You will also need to get rid of $ if you want to be able to successfully match the string, without worrying about how it ends.
const sampleIDs = [
"123456789000",
"123456abc",
];
sampleIDs.forEach(id => {
const clean = id.match(/^\d{6}[\d\D]/);
console.log(clean[0]);
});
This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
How to properly escape characters in regexp
(4 answers)
Closed 4 years ago.
I can't understand when I need one and two backward slashes \.
First, see an example:
const rxHttps = new RegExp("\/");
console.log(rxHttps.test("/")); // true
const rxQuestion = new RegExp("\\?");
console.log(rxQuestion.test("?")); // true
const rxAnotherQuestion = new RegExp("\?"); // Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
In the above example, to use a character /, it needs just one \.
However, ? needs two \, or SyntaxError occurs.
This is really confusing. I can't make heads or tails of it.
Why are they different? Am I misunderstanding?
because '?' is used to mean that what's before it can or not exist like {0,}
for example
var reg = new RegExp('a?');
// this has the same meaning as using
// var reg = new RegExp('a\?');
reg.test('a'); // will display true
reg.test('anything'); // this will also display true
reg.test('123'); // this also displays true
so if you want to check of the existence of '?' character, you have to escape it, and since it's used as '\?' also, then you have to escape it using '\?'
Why does it give you syntax error ?
because it's expecting something to check if it exists or not and you're not giving it anything.
This question already has answers here:
Numeric validation with RegExp to prevent invalid user input
(3 answers)
Closed 7 years ago.
I need a regex for any number OR float.
I have used this but doesn't work:
/(^[0-9]+*[.][0-9]+)$|^[\d+]$/
Why ?
Try this regex:
/^[+-]*[0-9]+[.][0-9]+|[+-]*[0-9]+$/g
You can use http://www.regexr.com/ to test and create regexes
Try this one:
^[-+]?[0-9]*\.?[0-9]+$
In case this might help you. This online Regex Tools is actually very helpful:
http://www.regexr.com/
You have a few issues with your regex:
You cannot have a quantifier after + so change +* to just + (1 or more matches)
Move your start identifier ^ outside of the group, for consistency
hmmm, you seem to have edited your regex: but [^\d+] was looking for NOT a number or + symbol.
One possible solution would be as follows:
^([0-9]+[.][0-9]+)$|^\d+$
Here is a working example
For more example, see here
You expression doesn't work because it contains errors.
This is the website I use for RegEx testing - It is good to test them on a website like this that gives you feedback
You have the beginning inside a capturing group, but the end outside - (^...)$
You also have double operators - +* - Use only one
And the or not plus sign and digit is not needed - ?[^\d+]
I believe this expression will do what you want: ^-?\d+(\.\d+)?$
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');