Regexp for all numbers or just one specific symbol - javascript

I need to verify if string consists of numbers only or just with one '*' symbol.
Correct:
*
123
5
Incorrect:
**
23*
*2
abc
I've tried new RegExp('[\*?|\d*]') but it doesn't allow numbers and allow multiple *

what about that : ^(?:\*|\d+)$
?: is for non capturing group.

Try this regex: "^\d*$"
^: start of the string, $: end of the string

There You go :
(^\*{1}$|^\d+$)
tested in notepad++

The solution using RegExp.test and String.match functions:
var checkString = function(str){
var ast_matches = str.match(/[*]/g); // asterisk symbol matches
return /^[*\d]+$/.test(str) && (!ast_matches || ast_matches.length === 1);
};
console.log(checkString("1235")); // true
console.log(checkString("*1235")); // true
console.log(checkString("**23*2abc")); // false

I would use this regex: ^(\*|[0-9]*)$:
^...$ for matching the whole line
(|) for defining two alternatives
\* alternative 1: one star only
[0-9]* alternative 2: numbers only
You can play with the regex here.
You can create the regex object like this: new RegExp(/^[0-9]*\*?[0-9]*$/); I.e. without the apostrophes. You can play with that here.

Related

Regex match with 3 condition?

I will creating math program .If i wish to solve i need separate to the equation using with regex.
For example:
`10x-10y2+100x-100k=100`
the format will separate with regex output: "10x" ,"100x" ,"100k" ,"10y2","100"
I have already code for that with separate match function
There are:
for num[a-z]num : ` /([\-+])?\s*(\d+)?([a-z]?(\d+))/g`
for num[a-z] : ` /([\-+])?\s*(\d+)?([a-z]?(\d+))/g`
fon num : `/\b[+-]?[\d]+\b/g`
I need all this three match function within one regex match function.some one help to combine the code with single regex expression
Note :i need match function only not a split beacause i apply that regex expression into parser
Thank You.
Split on symbols:
"10x-10y2+100x-100k=100".split(/[-+=]/);
Output:
["10x", "10y2", "100x", "100k", "100"]
If you need to use match() method I suggest same approach:
"10x-10y2+100x-100k=100".match(/[^-+=]+/g);
Output is the same.
/(?:0|[1-9]\d*)?(?:[a-z]+)?(?:\^(?:0|[1-9]\d*))?/g
// finds:
// vvv vvvvv vvvv vvvv vvvvv vv vvv v vvv
10x-10y^2+100x-100k=100^4+xy+100+100y2+0-1^0
// doesn't find: ^^^^^
(?:0|[1-9]\d*)? 0, OR 1-9 then zero or more numbers. Optional.
(?:[a-z]+)? Optional one or more lowercase letters.
(?:\^[1-9]\d*)? Optional power.
\^ Literal text.
(?:0|[1-9]\d*) Zero, OR 1-9 then zero or more numbers.
If I've missed anything let me know and I'll incorporate it.
Just try with following regex:
/(\d+[a-z]?\d*)/g
example
Try this:
s.match(/\d+([A-Za-z]\d*)?/g)

Extract specific chars from a string using a regex

I need to split an email address and take out the first character and the first character after the '#'
I can do this as follows:
'bar#foo'.split('#').map(function(a){ return a.charAt(0); }).join('')
--> bf
Now I was wondering if it can be done using a regex match, something like this
'bar#foo'.match(/^(\w).*?#(\w)/).join('')
--> bar#fbf
Not really what I want, but I'm sure I miss something here! Any suggestions ?
Why use a regex for this? just use indexOf to get the char at any given position:
var addr = 'foo#bar';
console.log(addr[0], addr[addr.indexOf('#')+1])
To ensure your code works on all browsers, you might want to use charAt instead of []:
console.log(addr.charAt(0), addr.charAt(addr.indexOf('#')+1));
Either way, It'll work just fine, and This is undeniably the fastest approach
If you are going to persist, and choose a regex, then you should realize that the match method returns an array containing 3 strings, in your case:
/^(\w).*?#(\w)/
["the whole match",//start of string + first char + .*?# + first string after #
"groupw 1 \w",//first char
"group 2 \w"//first char after #
]
So addr.match(/^(\w).*?#(\w)/).slice(1).join('') is probably what you want.
If I understand correctly, you are quite close. Just don't join everything returned by match because the first element is the entire matched string.
'bar#foo'.match(/^(\w).*?#(\w)/).splice(1).join('')
--> bf
Using regex:
matched="",
'abc#xyz'.replace(/(?:^|#)(\w)/g, function($0, $1) { matched += $1; return $0; });
console.log(matched);
// ax
The regex match function returns an array of all matches, where the first one is the 'full text' of the match, followed by every sub-group. In your case, it returns this:
bar#f
b
f
To get rid of the first item (the full match), use slice:
'bar#foo'.match(/^(\w).*?#(\w)/).slice(1).join('\r')
Use String.prototype.replace with regular expression:
'bar#foo'.replace(/^(\w).*#(\w).*$/, '$1$2'); // "bf"
Or using RegEx
^([a-zA-Z0-9])[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#([a-zA-Z0-9-])[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
Fiddle

Regular expression to match 0 or 1

I need a regexp to match either 0 or 1 entered into a field and no other characters at all, neither numeric nor alphas. How can I do it?
Single character, 0 or 1:
/^[01]$/
Multiple 0s or 1s (any order, no other characters):
/^[01]+$/g
Demo (Just add a + for the second example. The gm at the end in the demo is just for the example because there are multiple lines for test cases)
A simple 0|1 expression should work.
([01])
http://rubular.com/r/TMu6vsx6Dn
If you only want the first occurrence, this will work as well.
(^[01])
http://rubular.com/r/i3brvRutCg
Try this regex: /^(0|1)$/
Example:
/^(0|1)$/.test(0); // true
/^(0|1)$/.test(1); // true
/^(0|1)$/.test(2); // false
/^(0|1)$/.test(1001) // false
I would suggest simple string evaluation here since you have only two known acceptable values in the input string:
var input; // Your input string assume it is populated elsewhere
if (input === '0' || input === '1') {
// Pass
}
Note the use of strict string comparison here to eliminate matches with truthy/falsey values.
If you are really hell-bent on a regex, try:
/^[01]$/
The key here is the beginning ^ and ending $ anchors.

java script Regular Expressions patterns problem

My problem start with like-
var str='0|31|2|03|.....|4|2007'
str=str.replace(/[^|]\d*[^|]/,'5');
so the output becomes like:"0|5|2|03|....|4|2007" so it replaces 31->5
But this doesn't work for replacing other segments when i change code like this:
str=str.replace(/[^|]{2}\d*[^|]/,'6');
doesn't change 2->6.
What actually i am missing here.Any help?
I think a regular expression is a bad solution for that problem. I'd rather do something like this:
var str = '0|31|2|03|4|2007';
var segments = str.split("|");
segments[1] = "35";
segments[2] = "123";
Can't think of a good way to solve this with a regexp.
Here is a specific regex solution which replaces the number following the first | pipe symbol with the number 5:
var re = /^((?:\d+\|){1})\d+/;
return text.replace(re, '$15');
If you want to replace the digits following the third |, simply change the {1} portion of the regex to {3}
Here is a generalized function that will replace any given number slot (zero-based index), with a specified new number:
function replaceNthNumber(text, n, newnum) {
var re = new RegExp("^((?:\\d+\\|){"+ n +'})\\d+');
return text.replace(re, '$1'+ newnum);
}
Firstly, you don't have to escape | in the character set, because it doesn't have any special meaning in character sets.
Secondly, you don't put quantifiers in character sets.
And finally, to create a global matching expression, you have to use the g flag.
[^\|] means anything but a '|', so in your case it only matches a digit. So it will only match anything with 2 or more digits.
Second you should put the {2} outside of the []-brackets
I'm not sure what you want to achieve here.

How to use regEx to return false when data not in range?

Sample data: Hello I'm 301
I need a regex to allow A-Z a-z 0-9 and space(s) only.
All other characters are not allowed. If detected, return false to javascript.
Based on the sample data above, it should return false because got a character which is not accetable===> '
How to write this in js.
I suggest the regex:
/^[A-Z0-9 ]+$/i.test(someinput);
This ensures that the input ONLY consists of the characters mentioned in the regex, by "anchoring" the regex from start-of-the-string (indicated by "^") until the end of string ("$").
The trailing "/i" on the regex makes it a case-insensitive match, relieving specification of both cases of the letters.
Any string in Javascript has a match() function that accepts a regex and returns null if it doesn't match.
For instance, if you have:
var s = "Hello I'm 301";
you can test it with:
if (s.match(/^[a-z0-9\s]*$/i))
alert("string is ok!");
else
alert("string is bad!");
On to the regex: /^[a-z0-9\s]*$/i
The caret(^) at the beginning and the dollar ($) at the end are anchors. They mean "beginning of string" and "end of string".
They force the regex to cover the entire string, not just portions. The square brackets define a character range: letters and numbers, and also space.
Without the caret and the dollar (the anchors), your regex would have matched any valid character and would have returned true.
The final "i" is a regexp option, meaning "case insensitive".
Hope that helps!
Try this
function check(s){
return /^[A-Za-z0-9 ]+$/.test(s);
}
You'll probably want to use: /[A-Za-z0-9 ]*/.test(someInputString)
--edit: as noted in comments and other answers, the regex should be /^[A-Za-z0-9 ]*$/
You need to create the Javascript Regex object first.
var MyRegex = new RegExp(/^[a-zA-Z0-9\s]+$/)
or simply
var MyRegex = /^[a-zA-Z0-9\s]+$/
You can then use this to test, which will return a boolean
var MyString = "Hello I'm 301"
if (MyRegex.test (MyString))
{
// Would be true here
}
else
{
// Would be false here
// Would fall through to here due to '
}
I believe you can also do /^[a-zA-Z0-9\s]+$/.text(MyString)
Try this:
var x = 'Hello I\'m 301';
var z = x.match(/^[A-Za-z0-9\s]+$/g);
alert(z);
x = 'Hello Im 301';
var y = x.match(/^[A-Za-z0-9\s]+$/g);
alert(y);
Don't forget to escape the single quote in the test string :)
You can return true/false by checking for null after the regex match, if the sample string fails the match then the result is null.

Categories

Resources