I am trying to implement a function in Javascript that verify a string.
The pattern i must to do is contain only digits charactor, *, # and +.
For example:
+182031203
+12312312312*#
+2131*1231#
*12312+#
#123*########
I tried alot of thing like
/^[\d]{1,}[*,#,+]{1,}$
but it's doesn't work. I am not sure that i understand good in regex. Please help.
I think you want the pattern ^[0-9*#+]+$:
var inputs = ["+182031203", "+12312312312*#", "+2131*1231#", "12312+#", "#123########"];
for (var i=0; i < inputs.length; ++i) {
console.log(inputs[i] + " => " + /^[0-9*#+]+$/.test(inputs[i]));
}
Using Regex101
/^[0-9\*\#\+]+$/g
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
* matches the character * with index 4210 (2A16 or 528) literally (case sensitive)
# matches the character # with index 3510 (2316 or 438) literally (case sensitive)
+ matches the character + with index 4310 (2B16 or 538) literally (case sensitive)
Try this regular expression:
const rxDigitsAndSomeOtherCharacters = /^(\d+|[*#]+)+$/;
Breaking it down:
^ start-of-text, followed by
( a [capturing] group, consisting of
\d+ one or more digits
| or...
[*#+]+ one ore more of *, # or +
)+, the [capturing] group being repeated 1 or more times, and followed by
$ end-of-text
Related
I would like to extract values from a string semicolon separated values that could also contains semicolon but not as separator. The RegEx I found on this website (I lost the post) is almost complete because it separates the key and it's value.
Example:
my.parameter 10; the.foo "Procedural Map"; pve; server.description "This; is \"my\", my description,.\n"
Current result with [^; "]+|"(?:\\"|[^"])*"/g
[
'server.seed',
'10',
'pve',
'server.level',
'"Procedural Map"',
'server.description',
'"This; is \\"my\\", server; description,."'
]
Desired result
[
'my.parameter 10',
'the.foo "Procedural Map"',
'pve',
'server.description "This; is \"my\", server; description,.\n"'
]
Can you help me to improve the RegEx to group the parameter and it's value?
You could use a repeating pattern to first match any char except the ; and then optionally match from an opening till closing double quote and match the escaped double quotes in between.
After that optionally repeat the character class [^";\\]* to also match what comes after the closing double quote.
[^;"\\]+(?:"(?:[^"\\]*(?:\\.[^"\\]*)*)"[^";\\]*)*
[^;"\\]+ Match 1+ times any char except ; " \
(?: Non capture group to repeat as a whole
" Match literally
(?: Non capture group
[^"\\]* Match 0+ times any char except " \
(?:\\.[^"\\]*)* Optionally repeat matching \ and any char followed by 0+ times any char except " and \
) Close the non capture group
" Match literally
[^";\\]* Optionally match any char except " ; \
)* Close the outer non capture group and optionally repeat
Regex demo
I found a workaround by replacing separator by the ASCII separator (␟) then splitting the result.
const separatorPattern = /; (?=([^"]*"[^"]*")*[^"]*$)/g;
const myRawString = "server.seed 10; server.pve, server.level \"Procedural Map\"; server.description \"This; is \\\"my\\\", server; description,.\"";
const replacedSeparator = myRawString.replace(separatorPattern, "␟");
const parameters = replacedSeparator.split("␟");
console.log(parameters);
/*[
'server.seed 10',
'server.pve, server.level "Procedural Map"',
'server.description "This; is \\"my\\", server; description,."'
]*/
I have this regex that should match when there's two numbers in brackets
/(P|C\(\d+\,{0,1}\s*\d+\))/g
for example:
C(1, 2) or P(2 3) //expected to match
C(43) or C(43, ) // expect not to match
but it also matches the ones with only 1 number, how can i fix it?
You have a couple of issues. Firstly, your regex will match either P on its own or C followed by numbers in parentheses; you should replace P|C with [PC] (you could use (?:P|C) but [PC] is more performant, see this Q&A). Secondly, since your regex makes both the , and spaces optional, it can match 43 without an additional number (the 4 matches the first \d+ and the 3 the second \d+). You need to force the string to either include a , or at least one space between the numbers. You can do that with this regex:
[PC]\(\d+[ ,]\s*\d+\)
Demo on regex101
Try this regex
[PC]\(\d+(?:,| +) *\d+\)
Click for Demo
Explanation:
[PC]\( - matches either P( or C(
\d+ - matches 1+ digits
(?:,| +) - matches either a , or 1+ spaces
*\d+ - matches 0+ spaces followed by 1+ digits
\) - matches )
You can relax the separator between the numbers by allowing any combination of command and space by using \d[,\s]+\d. Test case:
const regex = /[PC]\(\d+[,\s]+\d+\)/g;
[
'C(1, 2) or P(2 3)',
'C(43) or C(43, )'
].forEach(str => {
let m = str.match(regex);
console.log(str + ' ==> ' + JSON.stringify(m));
});
Output:
C(1, 2) or P(2 3) ==> ["C(1, 2)","P(2 3)"]
C(43) or C(43, ) ==> null
Your regex should require the presence of at least one delimiting character between the numbers.
I suppose you want to get the numbers out of it separately, like in an array of numbers:
let tests = [
"C(1, 2)",
"P(2 3)",
"C(43)",
"C(43, )"
];
for (let test of tests) {
console.log(
test.match(/[PC]\((\d+)[,\s]+(\d+)\)/)?.slice(1)?.map(Number)
);
}
Create a function that given a string, retains only the letters A-Z (upper and lowercase), 0-9 digits, and whitespace characters. Also, returns "Not a string!" if the entry type is not a string.
So far, I have:
function notAString(string) {
var regex = new RegExp(`^(?=.*[A-Za-z])\d\s`, 'g');
if (regex.test(string)) {
return "String!";
} else {
return "Not a string!";
}
}
I am only getting "Not a string!" returned, even if it is a string.
I'm not sure many people would agree with your definition of string! But based on the sequence you described, that would be ^[A-Za-z0-9\s]+$
Check it out at https://regex101.com/
Your RegEx should be ^[A-Za-z 0-9]*$:
Where
^ asserts position at start of a line
A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)
a-z matches a single character in the range between a (index 97) and z (index 122) literally (case sensitive)
matches the space character
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) literally (case sensitive)
* quantifier — matches between zero and unlimited times, as many times as possible, giving back as needed
$ asserts position at the end of a line
You can also use Conditional (ternary) operator to simplify the solution like the following way:
function notAString(string) {
var regex = new RegExp(`^[A-Za-z 0-9]*$`, 'g');
return regex.test(string)? 'String!' : 'Not a string!';
}
console.log(notAString('123 Test string')); // String!
console.log(notAString('Test#string')); // Not a string!
I'm working on a pattern for a password with the following requirements:
Min character = 6
Max character = 64
Min 1 lowercase character
Min 1 uppercase character
Min 1 number
Min 1 special characters
I am using this regex:
var passReg = /^(?=^[ -~]{6,64}$)(?=.*([a-z][A-Z]))(?=.*[0-9])(.*[ -/|:-#|\[-`|{-~]).+$/;
However, it does not work as expected.
You must be looking for this regex:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[ -/:-#\[-`{-~]).{6,64}$
See demo
Here is explanation:
^ - Beginning of string
(?=.*[a-z]) - A positive look-ahead to require a lowercase letter
(?=.*[A-Z]) - A positive look-ahead to require an uppercase letter
(?=.*[0-9]) - A positive look-ahead to require a digit
(?=.*[ -/:-#\[-{-~])` - A positive look-ahead to require a special character
.{6,64} - Any character (but a newline), 6 to 64 occurrences
$ - End of string.
Are consider special non-whitespace characters. I think this is complite list:
! " # $ % & ' ( ) * + , - . / :
; < = > ? # [ \ ] ^ _ ` { | } ~
Try this one:
var passReg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!"#$%&'()*+,-.\/:;<=>?\\#[\]^_`{|}~]).{6,64}$/;
Look at back reference for special characters. In character sets chars like \ and ] must be escaped.
I'm sort of new to regular expressions, and none of the solutions I found online helped/worked.
I'm dealing with a one-line String in JavaScript, it'll contain five types of data mixed in.
A "#" followed by six numbers/letters (HTML color) (/#....../g)
A forward slash followed by any of a few specific characters (/\/(\+|\^|\-|#|!\+|_|#|\*|%|&|~)/g)
A "$" followed by a sequence of letters and a "|" (/\$([^\|]+)/g)
A "|" alone (/\|/g)
Alphanumeric characters that do not fall under any of these categories
The thing is, I have regexes to match the first four categories, that are important.
The problem is that I need a single Regex that I'll use to replace all the characters that DO NOT match for the first four regexes with a single character, such as "§".
Example:
This#00CC00 is green$Courier| and /^mono|spaced
§§§§#00CC00§§§§§§§§§$Courier|§§§§§/^§§§§|§§§§§§
I know I may be attacking this problem the wrong way, I'm rather new to regular expressions.
Essentially, how do I make a regex that means "anything that doesn't have any matches for regexes x, y, or z"?
Thank you for your time.
use this pattern
((#\w{6}|\/[\/\(\+\^\-]|\$\w+\||\|)*).
and replace w/ $1§
Downside is your preserved pattern has to be followed by at least one character
Demo
( # Capturing Group (1)
( # Capturing Group (2)
# # "#"
\w # <ASCII letter, digit or underscore>
{6} # (repeated {6} times)
| # OR
\/ # "/"
[\/\(\+\^\-] # Character Class [\/\(\+\^\-]
| # OR
\$ # "$"
\w # <ASCII letter, digit or underscore>
+ # (one or more)(greedy)
\| # "|"
| # OR
\| # "|"
) # End of Capturing Group (2)
* # (zero or more)(greedy)
) # End of Capturing Group (1)
. # Any character except line break
Code copied from Regex101
var re = /((#\w{6}|\/[\/\(\+\^\-]|\$\w+\||\|)*)./gm;
var str = 'This#00CC00 is green$Courier| and /^mono|spaced|\n';
var subst = '$1§';
var result = str.replace(re, subst);
This isn't as efficient as a working regular expression but it works. Basically it gets all of the matches and fills the parts between with § characters. One nice thing is you don't have to be a regular expression genius to update it, so hopefully more people can use it.
var str = 'This#00CC00 is green$Courier| and /^mono|spaced';
var patt=/#(\d|\w){6}|\/(\+|\^|\-|#|!\+|_|#|\*|%|&|~)|\$([^\|]+)\||\|/g;
var ret = "";
pos = [];
while (match=patt.exec(str)) {
pos.push(match.index);
pos.push(patt.lastIndex);
console.log(match.index + ' ' + patt.lastIndex);
}
for (var i=0; i<pos.length; i+=2) {
ret += Array(1+pos[i]- (i==0 ? 0 : pos[i-1])).join("§");
ret += str.substring(pos[i], pos[i+1]);
}
ret += Array(1+str.length-pos[pos.length-1]).join("§");
document.body.innerHTML = str +"<br>"+ret;
console.log(str);
console.log(ret);
demo here