I have the following string:
/xyz/10.2005/abc.d10.1/example
Here what I want to validate is, there should not be a space after "/xyz/".
Like It should not accept if the string is:
/xyz/ 10.2005/abc.d10.1/example
But it should accept if the string is:
10.2005/abc.d10.1/example
How can I modify the following regex to validate the above thing??
REGEX- "^\\S*((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?)"
Could someone help me??
This may be what you are looking for (it's a literal, you can convert it to a string if you really need to use the RegExp constructor):
var re = /^(\/\w+\/10|\s*10)\.\d+\/\w+\.\w\d+\.\d\/\w{7}/;
var s = '/xyz/10.2005/abc.d10.1/example';
var t = '/xyz/ 10.2005/abc.d10.1/example';
var u = ' 10.2005/abc.d10.1/example';
console.log(
's:' + re.test(s) + '\n' + // true
't:' + re.test(t) + '\n' + // false
'u:' + re.test(u) + '\n' // true
);
It does more than just validate the space after the /xyz/ part, I hope the rest is what you want.
actually you need to make it a lazy regex
just change it to this
^\\S*?((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?).*
see those ? and .* at the end
demo here : http://regex101.com/r/zJ7yX8
Here's a long RegEx:
/(?:\/[a-z]+\/)?\10\.\d{4}\/[a-z]{3}\.[a-z]\d{2}\.\d\/[a-z]{7}/i
// or the following if you don't want exact occurrences
/(?:\/[a-z]+\/)?10\.\d+\/[a-z]+\.[a-z]\d+\.\d\/[a-z]+/i
Matches:
/xyz/10.2005/abc.d10.1/example
10.2005/abc.d10.1/example
?: makes the group non-capturing.
The ? after the bracket-end symbolize it is optional.
Next is fairly simple RegEx.
For more explanation, here's a demo
Related
For example
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "") //Thisismystring
Now that all the whitespaces have been removed, how do I put them back in the exact position?
Additionally, let's suppose the replaced string undergoes some change and becomes
let myChangedString = "(T)(h)(i)(s)(i)(s)(m)(y)(s)(t)(r)(i)(n)(g)";
Now I want to put the whitespaces back where they used to be i.e after (s) and before (i), after (s) and before (m), after (y) before (s)
I've spent a couple of hours on this and been stuck in the same position, any form of help would be greatly appreciated.
EDIT: Solved, thank you very much.
The trick here is to replace the spaces with another character - rather than just removing the space. That way - its a simple matter to replace the added character with a space to return the spaces to where they started. When I do this - I always use the tilde character "~" since it is easily recognisable as well as unlikely to actually be used in a string.
I have added a few variations / modifications as well as the example you have provided with every character being wrapped in parentheses - just note that you will need to escape these when replaceing the (~) for the " " space character.
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "~");
console.log(replacedString);//This~is~my~string
let modifiedString = replacedString.replace(/my/g, "your");
console.log(modifiedString);//This~is~your~string
let spacedString = modifiedString.replace(/~/g, " ");
console.log(spacedString);//This is your string
// using your example of wrapping each character in parentheses
let myChangedString = "(" + modifiedString.split('').join(")(") + ")";
console.log(myChangedString); //(T)(h)(i)(s)(~)(i)(s)(~)(y)(o)(u)(r)(~)(s)(t)(r)(i)(n)(g)
let mySpacedString = myChangedString.replace(/\(~\)/g, " ");
console.log(mySpacedString); //(T)(h)(i)(s) (i)(s) (y)(o)(u)(r) (s)(t)(r)(i)(n)(g)
Why not replace only the parts you need to be replaced?
For example search for word character and replace with the wanted parts.
console.log("This is my string".replace(/\w/g, '($&)'));
Better you just transform your original array. Loop through array and modify the char is not empty.
let myString = "This is my string";
let chars = [...myString].map(item => item !== ' ' ? '(' + item + ')': item)
console.log(chars.join(''))
Are you looking for this...
var result = "thisismystring".replace(/^(.{4})(.{2})(.{2})(.*)$/, "$1 $2 $3 $4");
alert(result);
I have following regular expression to check only one decimal point for type number tag in html
^-?[0-9]*\\.?[0-9]*$
but this regular failed to check If I put decimal at the end e.g 12.12.
what further I have to add to check this
I think your regex can be easily fixed using a + instead of last * quantifier:
^-?[0-9]*\.?[0-9]+$
Tests:
const regex = /^-?[0-9]*\.?[0-9]+$/gm;
console.log('regex.test?')
console.log('12 = ' + regex.test('12'));
console.log('12. = ' + regex.test('12.'));
console.log('12.1 = ' + regex.test('12.1'));
console.log('12.12. = ' + regex.test('12.12.'));
console.log('-1 = ' + regex.test('-1'));
console.log('-1. = ' + regex.test('-1.'));
console.log('-1.2 = ' + regex.test('-1.2'));
console.log('-.12 = ' + regex.test('-.12'));
console.log('-. = ' + regex.test('-.'));
console.log('-. = ' + regex.test('-'));
console.log('. = ' + regex.test('.'));
Demo
Can you try the below : [1-9]\d*(\.\d+)?$
The simplest way to allow a possible . at the end is to have \.? just before the $. Also, the double \ looks wrong (unless you need it for escaping a \ in the context in which you are using it):
^-?[0-9]*\.?[0-9]*\.?$
But please recognize that your regex does not require any actual digits, so will match some non-numbers, like ., -. and (with my edit) -.. The above regex will also match an empty string!
You will want to either change your regex to require digits, or take into account somewhere else that they might not be there.
I have a variable which contains "j_id0:j_id11:i:f:pb:d:MyFieldName.input" (without the quotes).
Now I would like to capture "MyFieldName".
I had this:
var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var testRE = test.match(":(.*).input");
console.log("old text: " + test);
console.log("new text: " + testRE[1]);
which outputs this:
old text: j_id0:j_id11:i:f:pb:d:MyFieldName.input
new text: j_id11:i:f:pb:d:MyFieldName
So what I need is telling him that I want everything between the last occurence ":" and ".input", because now he finds the first ':' and stops there.
Any ideas how I can realise this?
Thanks!
One option that remains (among, presumably, many others) is:
var str = "j_id0:j_id11:i:f:pb:d:MyFieldName.input",
fieldName = str.substring(str.lastIndexOf(':') + 1, str.lastIndexOf('.'));
JS Fiddle demo.
References:
String.lastIndexOf().
String.substring().
This regex will work:
.*:(.*)\.input
You could try this without regular expressions:
var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var fieldName = test.split(':').pop().split('.')[0];
The problem with your regex is that it matches the first :, and then captures everything (.*) up until .input. To avoid this, you can make sure that your capture between : and .input cannot include more :.
This regex should work for you:
/:(\w+)\.input/
Fiddle
var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var testRE = test.match(/:(\w+)\.input/)
console.log("old text: " + test);
console.log("new text: " + testRE[1]); //MyFieldName
Group 1 will contain your field name.
I think the above should work for you, but if you need more than \w characters, you could use this instead to allow for things like "...:My.Field.Name.input" and capture "My.Field.Name":
/:([^:]+)\.input/
I need to check if a string represents a valid namespace format. A namespace is comprised of ids separated with dots. Each id starts with an alphabetic character and continues with an alphanumeric character.
Valid namespaces:
"com.company.package"
"com.company"
"com"
Invalid namespaces:
"1com.company.package"
"com.1company"
"com.com%any"
".com.company"
"com.company."
"com "
" com"
""
"."
"com..company"
Currently I use this simple regexp but it really don't check all of those invalid namespaces:
if( /^[\w\.]$/.test( namespaceStr ) ) {
//valid namespace
} else {
//invalid namespace
}
Any better suggestion for a small and efficient way to check if a string represents a valid namespace?
Here is a little jsfiddle that you can use for testing this regular expression: http://jsfiddle.net/bA85y/
Edit: This one should work for every case:
/^(?:[a-z]\d*(?:\.[a-z])?)+$/i
If you don't care about capturing groups even shorter:
/^([a-z]\d*(\.[a-z])?)+$/i
A little explanation:
^ // Start
( // Open group
[a-z]\d* // Must start by letter and may be followed by a number (greedy)
(\.[a-z])? // It may be followed by a dot only if it's followed by a letter (non-greedy)
)+ // Close group and match at least once so we get rid of empty values
$ // Ends, not allow any other characters
Demo: http://jsfiddle.net/elclanrs/5hnQV/
Try this pattern:
/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)*$/i
EDIT:
this is a reversion of #elclanrs jsfiddle
I think you are looking for this:
/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i
EDIT:
This one is a little better (with ?: and \d inspired by #HashemQolami and #elclanrs):
/^[a-z][a-z\d]*(?:\.[a-z][a-z\d]*)*$/i
And this one is shorter but does the same job:
/^[a-z](?:[a-z\d]*(?:\.[a-z])?)*$/i
And this one too, using lookahead to test that it doesn't end with a .:
/^(?!.*\.$)(?:[a-z][a-z\d]*\.?)+$/i
Please note that the selected answer doesn't work with "a.b.c" or in some cases with more than two levels.
UPDATE:
I've made a little (very basic) test:
var valid = [
"com.company.package",
"com.company",
"com.company1",
"com1.company1",
"a.b.c",
"a1.b.c3.d",
"a1.b2.c3.d4"];
var invalid = [
"1com.company.package",
"com.1company",
"com.com%any",
".com.company",
"com.company.",
"com ",
" com",
"",
".",
"com..company"];
function testRegex(regex, list)
{
var res=[];
for(var i=0; i<list.length; i++)
{
if(regex.test(list[i]))
res.push(list[i] + " ==> matched");
else
res.push(list[i] + " ==> NOT matched");
}
return res.join('<br>');
}
var regex = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i;
var html = "<p>VALID</p>";
html += testRegex(regex, valid);
html += "<p>INVALID</p>";
html += testRegex(regex, invalid);
document.write("<div>" + html + "</div>");
Based on #dionyziz answer this work:
/^[a-z]+(\.[a-z]+)*[^.\s]$/
The following regular expression will do what you need. It checks for an alphabetic string and then allows multiple other alphabetic strings separated by a dot.
/^[a-z]+(\.[a-z]+)*$/
I've been trying to find a way to match a number in a Javascript string that is surrounded by parenthesis at the end of the string, then increment it.
Say I have a string:
var name = "Item Name (4)";
I need a RegExp to match the (4) part, and then I need to increment the 4 then put it back into the string.
This is the regex I have so far:
\b([0-9]+)$\b
This regex does not work. Furthermore, I do not know how to extract the integer retrieved and put it back in the same location in the string.
Thanks.
The replace method can take a function as its second argument. It gets the match (including submatches) and returns the replacement string. Others have already mentioned that the parentheses need to be escaped.
"Item Name (4)".replace(/\((\d+)\)/, function(fullMatch, n) {
return "(" + (Number(n) + 1) + ")";
});
I can can only think of a way of doing it in three steps: Extract, increment and replace.
// Tested on rhino
var name = "Item Name (4)";
var re = /\((\d+)\)/;
match = re.exec(name);
number = parseInt(match[1]) + 1;
name = name.replace(re, "(" + number + ")");
The important parts of the pattern:
You need to escape the parens to match literal parens
You also need the to use parens to capture the number so that you can extract it from the match.
\d matches a digit and is shorter and more common than writing out [0-9].
In order this pattern to work you shoud escape parenthesis. In addition \b and $ are unneeded. Thus
var s = "Item Name (4)";
var match = /\((\d+)\)/.exec( s );
var n = Number(match[1])+1;
alert( s.replace( /\(\d+\)/, '('+n+')' ) );
Solution by david.clarke (tested)
"Item Name (4)".replace(/\(([0-9]+)\)/, '('+(1+RegExp.$1) + ')');
But I think it is too concise
UPD: It turned out that RegExp.$1 can't be used as part of replace parameter, because it works only in Opera
'var name = "Item Name (4)"'.replace(/\(([\d]+)\)/, 1 + $1);
(untested)