I'm trying to write a Regex
What I need is:
To start only with: A-z (Alphabetic)
Min. Length: 5
Max. Length: 10
The rest can be A-z0-9(Alphanumeric) but contain at least one number
What I have: ^[A-z][A-z0-9]{5,10}$
You can use
/^(?=.{5,10}$)[a-z][a-z]*\d[a-z\d]*$/i
See the regex demo
Details:
^ - start of string
(?=.{5,10}$) - the string should contain 5 to 10 any chars other than line break chars (this will be restricted by the consuming pattern later) up to the end of string
[a-z] - the first char must be an ASCII letter (i modifier makes the pattern case insensitive)
[a-z]* - 0+ ASCII letters
\d - 1 digit
[a-z\d]* - 0+ ASCII letters of digits
$ - end of string.
var ss = [ "ABCABCABC1","ABCA1BCAB","A1BCABCA","A1BCAB","A1BCA","A1BC","1BCABCABC1","ABCABC","ABCABCABCD"]; // Test strings
var rx = /^(?=.{5,10}$)[a-z][a-z]*\d[a-z\d]*$/i; // Build the regex dynamically
document.body.innerHTML += "Pattern: <b>" + rx.source
+ "</b><br/>"; // Display resulting pattern
for (var s = 0; s < ss.length; s++) { // Demo
document.body.innerHTML += "Testing \"<i>" + ss[s] + "</i>\"... ";
document.body.innerHTML += "Matched: <b>" + rx.test(ss[s]) + "</b><br/>";
}
var pattern = /^[a-z]{1}\w{4,9}$/i;
/* PATTERN
^ : Start of line
[a-z]{1} : One symbol between a and z
\w{4,9} : 4 to 9 symbols of any alphanumeric type
$ : End of line
/i : Case-insensitive
*/
var tests = [
"1abcdefghijklmn", //false
"abcdefghijklmndfvdfvfdv", //false
"1abcde", //false
"abcd1", //true
];
for (var i = 0; i < tests.length; i++) {
console.log(
tests[i],
pattern.test(tests[i])
)
}
Related
I have a string like "A < -5.9 AND B >= 6 OR (C < 3)" I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=
Simplest way would be to split using a regex:
"A < -5.9 AND B >= 6 OR (C < 3)".split(/ AND | OR /);
// ["A < -5.9", "B >= 6", "(C < 3)"]
We can try doing a regex search for all matches on the pattern:
\b([A-Z]+) \S+ -?\d+(?:\.\d+)?\b
Sample script:
var regex = /\b([A-Z]+) \S+ -?\d+(?:\.\d+)?\b/g;
var input = "A < -5.9 AND B >= 6 OR (C < 3)";
var m;
do {
m = regex.exec(input);
if (m) {
console.log(m[1]);
}
} while (m);
Here is an explanation of the regex pattern being used:
\b([A-Z]+) match and capture a key as one or more capital letters
\S+ match space followed by a symbol and another space
-?\d+ match a number with optional negative sign
(?:\.\d+)?\b match an optional decimal component
Without regex you caniterate the string and match the character > or <. If the character matches then create a substring and then get the last character of the substring. Also note trim() will remove any white space from the string
let str = 'A < -5.9 AND B >= 6 OR (C < 3)';
let arr = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === '<' || str[i] === '>') {
let subStr = str.substring(0, i).trim();
arr.push(subStr.charAt(subStr.length - 1))
}
};
console.log(arr);
If it's just a matter of capturing variable names that appear to the left of a comparison operator:
const s = "A < -5.9 AND B >= 6 OR (C < 3)";
const variables = s.match(/\w+(?=\s*[<>])/g);
console.log(variables);
This question already has answers here:
How to convert "camelCase" to "Camel Case"?
(12 answers)
Closed 6 years ago.
I am trying to figure out how to insert a character after a lower case letter but before an upper case letter in a string wherever it occurs. For instance, with the string "HiMyNameIsBob", if I were inserting spaces I would want it to return "Hi My Name Is Bob". I want to do something similar to what replace() does. I am using JavaScript.
If the answer involves any use of regular expressions, an explanation of the regular expression(s) used would be nice.
var string = 'HiMyNameIsBob';
string = string.replace(/([a-z])([A-Z])/g, '$1 $2')
will insert a space after each occurrence of a lower case character followed by an upper case character.
[a-z] any lower char from a to z
[A-Z] any upper char from a to z
/g means global
'$1 $2' are wildcards
var insertSpace = function(string) {
var chars = string.split('');
var insert = ' ';
for (var i = 0; i < string.length; i++) {
var char = chars[i];
var nextChar = chars[i + 1] || null;
if (char === char.toLowerCase() && nextChar === nextChar.toUpperCase()) {
chars.splice(i + 1, 0, insert);
i++;
}
}
return chars.join('');
}
I'm trying to make a Regex in JavaScript to match each not escaped specific characters.
Here I'm looking for all the ' characters. They can be at the beginning or the end of the string, and consecutive.
E.g.:
'abc''abc\'abc
I should get 3 matchs: the 1st, 5 and 6th character. But not 11th which escaped.
You'll have to account for cases like \\' which should match, and \\\' which shouldn't. but you don't have lookbehinds in JS, let alone variable-length lookbehinds, so you'll have to use something else.
Use the following regex:
\\.|(')
This will match both all escaped characters and the ' characters you're looking for, but the quotes will be in a capture group.
Look at this demo. The matches you're interested in are in green, the ones to ignore are in blue.
Then, in JS, ignore each match object m where !m[1].
Example:
var input = "'abc''abc\\'abc \\\\' abc";
var re = /\\.|(')/g;
var m;
var positions = [];
while (m = re.exec(input)) {
if (m[1])
positions.push(m.index);
}
var pos = [];
for (var i = 0; i < input.length; ++i) {
pos.push(positions.indexOf(i) >= 0 ? "^" : " ");
}
document.getElementById("output").innerText = input + "\n" + pos.join("");
<pre id="output"></pre>
You can use:
var s = "'abc''abc\\'abc";
var cnt=0;
s.replace(/\\?'/g, function($0) { if ($0[0] != '\\') cnt++; return $0;});
console.log(cnt);
//=> 3
I want to cut a string every 100 characters without cutting up words.
var TmpArray=[];
var str = 'this string will be cut up after every 100 characters but it will cut into words';
str=str.replace(/[^a-z A-Z0-9]+/g, '');
str = str.replace(/\s{2,}/g, ' ');
var sp=(str.match(new RegExp(" ", "g")) || []).length;
var max=100;
//Spaces will be converted into %20 (later) so each space must count as 3 characters.
var FoundSpaces=sp*3;
var tmp=max-FoundSpaces;
var cut=str.match(new RegExp('.{1,'+tmp+'}', 'g'));
for (i = 0; i < cut.length; i++){
TmpArray.push(cut[i]);
}
console.log(TmpArray);
Output: ["this string will be cut up after every 100 characters b", "ut it will cut into words"]
So how can I prevent it from splitting words like it did?
Interesting question. I will propose one more implementation of how you can use just array methods, combination of split + reduce:
var str = 'This example of the string that we want to split by spaces only making sure that individual chunk is less or equal to specified number.';
// Split by spaces
str.split(/\s+/)
// Then join words so that each string section is less then 40
.reduce(function(prev, curr) {
if (prev.length && (prev[prev.length - 1] + ' ' + curr).length <= 40) {
prev[prev.length - 1] += ' ' + curr;
}
else {
prev.push(curr);
}
return prev;
}, [])
// Print for testting
.forEach(function(str) {
console.log(str + ' ' + str.length);
});
For this example I set maximum length of 40 characters.
Output:
This example of the string that we want 39
to split by spaces only making sure that 40
individual chunk is less or equal to 36
specified number. 17
One more demo: http://jsfiddle.net/9tgo6n1t/
I have this string :
var a='abc123#xyz123';
I want to build 2 regexes replace functions which :
1) Replace all characters that do have a future '#' - with '*' (not including '#')
so the result should look like :
'******#xyz123'
2) Replace all characters that do not have a future '#' - with '*' (not including '#')
so the result should look like :
'abc123#******'
What have I tried :
For the positive lookahead :
var a='abc123#xyz123';
alert(a.replace(/(.+(?=#))+/ig,'*')); //*#xyz123 --wrong result since it is greedy...
Question :
How can I make my regexes work as expected ?
First part using lookahead:
repl = a.replace(/.(?=[^#]*#)/g, "*");
//=> "******#xyz123"
Explanation:
This regex finds any character that is followed by # using lookahead and replaced that with *.
Second part using replace callback:
repla = a.replace(/#(.*)$/, function(m, t) { return m[0] + t.replace(/./g, '*'); } );
//=> abc123#******
Explanation:
This code finds text after #. Inside the callback function is replaces every character with asterisk.
You can use indexOf and substr for this instead:
function maskBeforeAfter(before, str, character, maskCharacter) {
character = character || '#';
maskCharacter = maskCharacter || '*';
var characterPosition = str.indexOf(character);
if (characterPosition > -1) {
var mask = '';
if (before) {
for (var i = 0; i < characterPosition; i++) {
mask += maskCharacter;
}
return mask + str.substr(characterPosition);
} else {
for (var i = 0; i < str.length - characterPosition - 1; i++) {
mask += maskCharacter;
}
return str.substr(0, characterPosition + 1) + mask;
}
}
return str;
}
function maskBefore(str, character, maskCharacter) {
return maskBeforeAfter(true, str, character, maskCharacter);
}
function maskAfter(str, character, maskCharacter) {
return maskBeforeAfter(false, str, character, maskCharacter);
}
> var a = 'abc12345#xyz123';
> maskBefore(a);
"********#xyz123"
> maskAfter(a);
"abc12345#******"
If you insist on a simple regex:
The first one is already answered. The second can be written similarly:
a.replace(/[^#](?![^#]*#)/g, '*')
(?![^#]*#) is a negative lookahead that checks that there isn't a pound after the current character.
[^#] also checks that the current character isn't a pound. (we could have also used /(?![^#]*#)./g, but it is less pretty.
A positive option is:
a.replace(/[^#](?=[^#]*$)/g, '*');
this is very similar to the first one: (?=[^#]*$) checks that we have only non-pounds ahead, until the end of the string.
In both of this options, all characters in strings with no pounds will be replaces: "abcd" -> "****"