I want to make regular express which will allow only a-z and A-Z character between :: .
Like
My :head: is on :fire:
I have find something like this
/:.+?:/g
Which allow all character between ::
How to Allow only character a-z and A-Z ?
You can use /:[a-zA-Z]*:/g regex.
Have a look at the online demo.
Example code:
var re = /:[a-zA-Z]*:/g;
var str = ':mystring:';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Just put A-Z, a-z inside a character class and place it between the two colons.
:[A-Za-z]+:
+ after the character class will repeat the previous token one or more times. So this [A-Za-z]+ would match one or more alphabets.
In javascript, you need to use match function like
> var str = 'My :head: is on :fire:'
undefined
> str.match(/:[A-Za-z]+:/g)
[ ':head:', ':fire:' ]
:[a-z]+:
Try this with i modifier.
Related
I want to implement a function that outputs the respective strings as an array from an input string like "str1|str2#str3":
function myFunc(string) { ... }
For the input string, however, it is only necessary that str1 is present. str2 and str3 (with their delimiters) are both optional. For that I have already written a regular expression that performs a kind of split. I can not do a (normal) split because the delimiters are different characters and also the order of str1, str2, and str3 is important. This works kinda with my regex pattern. Now, I'm struggling how to extend this pattern so that you can escape the two delimiters by using \| or \#.
How exactly can I solve this best?
var strings = [
'meaning',
'meaning|description',
'meaning#id',
'meaning|description#id',
'|description',
'|description#id',
'#id',
'meaning#id|description',
'sub1\\|sub2',
'mea\\|ning|descri\\#ption',
'mea\\#ning#id',
'meaning|description#identific\\|\\#ation'
];
var pattern = /^(\w+)(?:\|(\w*))?(?:\#(\w*))?$/ // works without escaping
console.log(pattern.exec(strings[3]));
Accordingly to the problem definition, strings 0-3 and 8-11 should be valid and the rest not. myFunc(strings[3]) and should return ['meaning','description','id'] and myFunc(strings[8]) should return [sub1\|sub2,null,null]
You need to allow \\[|#] alognside the \w in the pattern replacing your \w with (?:\\[#|]|\w) pattern:
var strings = [
'meaning',
'meaning|description',
'meaning#id',
'meaning|description#id',
'|description',
'|description#id',
'#id',
'meaning#id|description',
'sub1\\|sub2',
'mea\\|ning|descri\\#ption',
'mea\\#ning#id',
'meaning|description#identific\\|\\#ation'
];
var pattern = /^((?:\\[#|]|\w)+)(?:\|((?:\\[#|]|\w)*))?(?:#((?:\\[#|]|\w)*))?$/;
for (var s of strings) {
if (pattern.test(s)) {
console.log(s, "=> MATCHES");
} else {
console.log(s, "=> FAIL");
}
}
Pattern details
^ - string start
((?:\\[#|]|\w)+) - Group 1: 1 or more repetitions of \ followed with # or | or a word char
(?:\|((?:\\[#|]|\w)*))? - an optional group matching 1 or 0 occurrences of
\| - a | char
((?:\\[#|]|\w)*) - Group 2: 0 or more repetitions of \ followed with # or | or a word char
(?:#((?:\\[#|]|\w)*))? - an optional group matching 1 or 0 occurrences of
# - a # char
((?:\\[#|]|\w)*) Group 3: 0 or more repetitions of \ followed with # or | or a word char
$ - end of string.
My guess is that you wish to split all your strings, for which we'd be adding those delimiters in a char class maybe, similar to:
([|#\\]+)?([\w]+)
If we don't, we might want to do so for validations, otherwise our validation would become very complicated as the combinations would increase.
const regex = /([|#\\]+)?([\w]+)/gm;
const str = `meaning
meaning|description
meaning#id
meaning|description#id
|description
|description#id
#id
meaning#id|description
sub1\\|sub2
mea\\|ning|descri\\#ption
mea\\#ning#id
meaning|description#identific\\|\\#ation`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Demo
Seems like what you're looking for may be this?
((?:\\#|\\\||[^\|#])*)*
Explanation:
Matches all sets that include "\#", "\|", or any character except "#" and "|".
https://regexr.com/4fr68
I have an input string
var input = 'J1,J2, J3';
I'm using the following pattern to extract the group value
var regex = /(,? ?(?<JOUR>J[0-9]+)+)/
while extracting the groups as below
var match = regex.exec(input);
match.groups contains only one group. How can i get all the groups J1 J2 and J3 from the input string ?
You can use .match of string to get groups
input.match(/J[0-9]+/g)
var input = 'J1,J2, J3';
console.log(input.match(/J[0-9]+/gi))
Match a capital J, then any amount of numbers:
var input = 'J1,J2, J3';
var regex = /J[0-9]+/g;
console.log(input.match(regex));
You could take the start of the string and the comma with an optional space into account and remove the outer group to use only 1 capturing group. To prevent the digits being part of a larger word you might add a word boundary \b
Note that you can omit the quantifier+ after )+ because that will repeat the group and will give you only the value of the last iteration.
(?:^|[,-] ?)(?<JOUR>J[0-9]+)\b
(?:^|[,-] ?) Match either the start of the string or comma or hyphen with an optional space
(?<JOUR>J[0-9]+) Named capture group JOUR, match J and then 1+ digits
\b Word boundary to prevent the digits being part of a larger word
Regex demo
Use exec to get the value from the first capturing group
const regex = /(?:^|, ?)(?<JOUR>J[0-9]+\b)+/g;
let m;
[
"J1, J2, J3 - J5, J7",
"J1,J2, J3"
].forEach(str => {
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m[1]);
}
});
const input = 'J1,J2, J3,J10';
const regexJfollowOneDigit = /(J\d{1}(?!\d))/g
const regexJfollowOneOrMoreDigit = /(J\d+)/g
console.log(input.match(regexJfollowOneDigit))
console.log(input.match(regexJfollowOneOrMoreDigit))
How to capitalize each words on starting of a string and after dot(.) sign?
I made a research on google and stackoverflow, below are the codes that I achieved but this will only capitalize starting of a string. Example as belows;
var str = 'this is a text. hello world!';
str = str.replace(/^(.)/g, str[0].toUpperCase());
document.write(str);
I want the string to be This is a text. Hello world!.
I have tried to use css, text-transform: capitalize; but this will result in each word to be capitalize.
I use a function like this, that takes an optional second parameter that will convert the entire string to lowercase initially. The reason is that sometimes you have a series of Title Case Items. That You Wish to turn into a series of Title case items. That you wish to have as sentence case.
function sentenceCase(input, lowercaseBefore) {
input = ( input === undefined || input === null ) ? '' : input;
if (lowercaseBefore) { input = input.toLowerCase(); }
return input.toString().replace( /(^|\. *)([a-z])/g, function(match, separator, char) {
return separator + char.toUpperCase();
});
}
The regex works as follows
1st Capturing Group (^|\. *)
1st Alternative ^
^ asserts position at start of the string
2nd Alternative \. *
\. matches the character `.` literally (case sensitive)
* matches the character ` ` literally (case sensitive)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Capturing Group ([a-z])
Match a single character present in the list below [a-z]
a-z a single character in the range between a (ASCII 97) and z (ASCII 122) (case sensitive)
You would implement it in your example like so:
var str = 'this is a text. hello world!';
str = sentenceCase(str);
document.write(str); // This is a text. Hello world!
Example jsfiddle
PS. in future, i find regex101 a hugely helpful tool for understanding and testing regex's
If you are using jquery, use this code
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
var str = "my name is Jhon. are you good. is it";
var str1 = str.split('.');
var str2 = "";
$.each(str1,function(i){
str2 += capitalize($.trim(str1[i]))+'. ';
});
console.log(str2);
catch the out put in str2.
in my case its like the following.
My name is Jhon. Are you good. Is it.
I always have a hard time with regex..
I'm trying to select the text between (taking into acount the before and after)
'window.API=' and ';' //for window.API= '--API--';
and other cases like:
'window.img_cdn=' and ';' //for window.img_cdn= '--imgCDN--';
any tips on witch regex concepts I should use would be a great help!
If you want to capture the content between 'xx' you can use a regex like this:
'(.*?)'
working demo
For the sample text:
window.API= '--API--';
window.img_cdn= '--imgCDN--';
You will capture:
MATCH 1
1. [13-20] `--API--`
MATCH 2
1. [40-50] `--imgCDN--`
The javascript code you can use is:
var re = /'(.*?)'/g;
var str = 'window.API= \'--API--\';\nwindow.img_cdn= \'--imgCDN--\';';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
On the other hand, if you specifically want to capture the content for only those entries, then you can use this regex:
window\.(?:API|img_cdn).*?'(.*?)'
If you want to match any text between a <some string>= sign and a semicolon, here you go:
(?:[\w\.]+\s*=\s')(.+)(?:';)$
This regex pattern will match a full string if an escaped apostrophe is present in the string: //for window.img_cdn = '--imgCDN and \'semicolon\'--';
JavaScript code:
var re = /(?:[\w\.]+\s*=\s')(.+)(?:';)$/gm;
var str = '//for window.img_cdn= \'--imgCDN--\';\n//for window.img_cdn = \'--imgCDN and semicolon = ;;;--\';';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// view results
}
The required text is in the 1st captured group. In case there is a semicolon in the text you are looking for, you will correctly match it due to the $ anchor.
See demo here
I need to check whether a string is valid price or not. In some locales, "." is interchanged with "," and separator could be at thousands or hundreds.
For Example:
Valid:
1234
1,234
1.234
1,23,334
1.23.334
1,23,334.00
1.23.334,00
Invalid:
1,23...233
1,,23
etc
The Regex I have used is
/(\d+(?:[\.,](?![\.,])\d+)*)/g
but this is giving me two matches for "1,23...233" i,e "1,23" and "233" as matches, I don't want to return any matches for that. Here is the regex I have been working on. What I actually want to do, whenever there is "." or "," next character should not be "." or "," and it should be a digit.
You can simply do this.
^\d+(?:[.,]\d+)*$
Try this.See demo.
https://regex101.com/r/tX2bH4/61
var re = /^\d+(?:[.,]\d+)*$/gm;
var str = '1234\n1,234\n1.234\n1,23,334\n1.23.334\n1,23,334.00\n1.23.334,00\n1,23...233\n1,23.';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Seems like you want something like this,
^\d+(?:\.\d+)?(?:,\d+(?:\.\d+)?)*$
DEMO
OR
^(?!.*(,,|,\.|\.,|\.\.))[\d.,]+$
Negative lookahead at the start asserts that the sting won't contain consecutive commas or dots or dots and commas.
DEMO