regex capturing group/alternative combination not working in quotes - javascript

I am trying to use this expression:
var reg = "/(jan|feb|mar)[A-z]*\[0-9]/"
to capture at least the first three letters of the month(or more letters) plus a digit. This does not work however. When I remove the parenthesis, it works but then the [A-z]*[0-9] bit only aplies to march. Please help, thanks.

Your regex is incorrect, also the regex should not be a string.
Use regex /(jan|feb|mar)[a-z]*[0-9]/i
Regex explanation: https://regex101.com/r/9Qv2dy/2
Snippet:
var reg = /(jan|feb|mar)[a-z]*[0-9]/i;
console.log('January1'.match(reg));

Your code contains several issues.
The /.../ regex literal should not be put inside quotes.
[A-z] matches more than just letters, you need [A-Za-z]
A \[ pattern matches a literal [ char. To match a digit, you need [0-9] or \d. To match 1 or more digits: [0-9]+ or \d+.
Use
var reg = /(?:jan|feb|mar)[a-z]*[0-9]/i;
See JS demo:
var reg = /(?:jan|feb|mar)[a-z]*[0-9]/i;
console.log("Date: January1".match(reg));

Related

Validate text with javascript RegEX

I'm trying to validate text with javascript but can find out why it's not working.
I have been using : https://regex101.com/ for testing where it works but in my script it fails
var check = "test"
var pattern = new RegExp('^(?!\.)[a-zA-Z0-9._-]+$(?<!\.)','gmi');
if (!pattern.test(check)) validate_check = false;else validate_check = true;
What i'm looking for is first and last char not a dot, and string may contain [a-zA-Z0-9._-]
But the above check always fails even on the word : test
+$(?<!\.) is invalid in your RegEx
$ will match the end of the text or line (with the m flag)
Negative lookbehind → (?<!Y)X will match X, but only if Y is not before it
What about more simpler RegEx?
var checks = ["test", "1-t.e_s.t0", ".test", "test.", ".test."];
checks.forEach(check => {
var pattern = new RegExp('^[^.][a-zA-Z0-9\._-]+[^.]$','gmi');
console.log(check, pattern.test(check))
});
Your code should look like this:
var check = "test";
var pattern = new RegExp('^[^.][a-zA-Z0-9\._-]+[^.]$','gmi');
var validate_check = pattern.test(check);
console.log(validate_check);
A few notes about the pattern:
You are using the RegExp constructor, where you have to double escape the backslash. In this case with a single backslash, the pattern is ^(?!.)[a-zA-Z0-9._-]+$(?<!.) and the first negative lookahead will make the pattern fail if there is a character other than a newline to the right, that is why it does not match test
If you use the /i flag for a case insensitive match, you can shorten [A-Za-z] to just one of the ranges like [a-z] or use \w to match a word character like in your character class
This part (?<!\.) using a negative lookbehind is not invalid in your pattern, but is is not always supported
For your requirements, you don't have to use lookarounds. If you also want to allow a single char, you can use:
^[\w-]+(?:[\w.-]*[\w-])?$
^ Start of string
[\w-]+ Match 1+ occurrences of a word character or -
(?: Non capture group
[\w.-]*[\w-] Match optional word chars, a dot or hyphen
)? Close non capture group and make it optional
$ End of string
Regex demo
const regex = /^[\w-]+(?:[\w.-]*[\w-])?$/;
["test", "abc....abc", "a", ".test", "test."]
.forEach((s) =>
console.log(`${s} --> ${regex.test(s)}`)
);

Capturing the character before the regex

I have a quick question about a regex that I wrote in JavaScript. It is the following (?<=,)(.*)(?=:) and it captures everything between , and :. I want it, however, to capture the comma itself too, as in.
So,<< this is what my regex captures at the moment>>: end would become
So<<, this is what my regex captures at the moment>>: end.
I tried using a . before the , in the regex but it doesn't seem to be working.
Use a simple capturing group - it's shorter than your current regex and works perfectly:
var regex = /(,.*?):/g;
var string = "So,<< this is what my regex captures at the moment>>: end";
console.log(string.match(regex));
Explanation:
() - denotes a capturing group
, - match a comma
.?* - match any amount of any characters
: - match a comma
Assuming the double arrows are for indicating the start and the end what your current pattern matches, you could match the comma and then 1+ times not a comma using a negated character class:
,[^:]+
If the comma at the end should be there, you could use the capturing group:
(,[^:]+):
Regex demo
You can omit the positive lookahead (?=:) by just matching the colon because you are already using a capturing group to get the match.
const regex = /(,[^:]+):/;
const str = `So,<< this is what my regex captures at the moment>>: end`;
let res = str.match(regex);
console.log(res[1]);
As you said :
So,<< this is what my regex captures at the moment>>: end would become
So<<, this is what my regex captures at the moment>>: end.
you could use replace like this :
var str = `So,<< this is what my regex captures at the moment>>: end`;
var replace = str.replace(/(.*?)(,)(<<)(.*)/,"$1$3$2$4");
console.log(replace);

Matching any character followed by not numbers

I am not good at RegEx. Though it seems very simple to achieve but I am not able to find out the way to match any characters followed by not numbers. I am trying with negative lookahead. If I use any word it is working as expected but if I try to match any character with square bracket, it is failing.
var pattern = /sample(?!\d)/;
console.log(pattern.test("sample324")); //false
var pattern = /[a-z]+(?!\d)/;
console.log(pattern.test("sample324")); //true but expect false
Thanks in advance.
Problem is that [a-z]+(?!\d) will let it match any 1+ characters not followed by a digit, so it will match sampl in your input satisfying assertion of non-digit at next position.
You may use this regex with a negative lookahead:
/^(?!.+\d)/
This will fail the match if a digit appears anywhere in input after 1+ of any character.
RegEx Demo
For better efficiency, you may use this regex as well:
/^(?!\D+\d)/
Which fails if there 1+ non-digits followed by a digit anywhere in input.
I think this may work:
var pattern = /[^0-9]/.test('mystring9')

Regular Expression for alphabets, numbers and symbols

I am looking for a regex for allowing
Alphabets case insensitive [a-zA-Z]
hyphen and underscore [-_]
forward and backward slashes [/\\\\]
numbers [0-9]
Hence
var regex = new RegExp('^[a-zA-Z-_][/\\\\]*$');
regex.test('ABC/90-1_AB');
does not work.
Your current regexp (/^[a-zA-Z-_][/\\\\]*$/) is looking for a string that start with a letter, - or _ who are then followed by 0 or more / or \ that end the string.
Put it inside 1 bracket :
'^[-_/0-9a-zA-Z\\\\]*$'
Try:
var regex = new RegExp('[\w\\/-]','i'); // \w matches alphanumeric characters and underscore
regex.test('ABC/90-1_AB'); // returns true
JSFIDDLE
Since you aren't willing to have complex RegExp why making it difficult, when you can just match your needs with explicitly required symbols

Finding Plus Sign in Regular Expression

var string = 'abcd+1';
var pattern = 'd+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
I found out last night that if you try and find a plus sign in a string of text with a Javascript regular expression, it fails. It will not find that pattern, even though it exists in that string. This has to be because of a special character. What's the best way to find a plus sign in a piece of text? Also, what other characters will this fail on?
Plus is a special character in regular expressions, so to express the character as data you must escape it by prefixing it with \.
var reg = /d\+1/;
\-\.\/\[\]\\ **always** need escaping
\*\+\?\)\{\}\| need escaping when **not** in a character class- [a-z*+{}()?]
But if you are unsure, it does no harm to include the escape before a non-word character you are trying to match.
A digit or letter is a word character, escaping a digit refers to a previous match, escaping a letter can match an unprintable character, like a newline (\n), tab (\t) or word boundary (\b), or a a set of characters, like any word-character (\w), any non-word character (\W).
Don't escape a letter or digit unless you mean it.
Just a note,
\ should be \\ in RegExp pattern string, RegExp("d\+1") will not work and Regexp(/d\+1/) will get error.
var string = 'abcd+1';
var pattern = 'd\\+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
//3
You should use the escape character \ in front of the + in your pattern. eg. \+
You probably need to escape the plus sign:
var pattern = /d\+1/
The plus sign is used in regular expressions to indicate 1 or more characters in a row.
It should be var pattern = '/d\\+1/'.
The string will escape '\\' as '\' ('\\+' --> '\+') so the regex object init with /d\+1/
if you want to use + (plus sign) or $ (sigil /dollar sign), then use \ (backslash) as a prefix. Like that:
\$ or \+

Categories

Resources