Regex catch from the hash sign "#" to the next white space - javascript

I have a script line this :
#type1 this is the text of the note
I've tried this bu didn't workout for me :
^\#([^\s]+)
I watch to catch type in other words I to get whats between the hash sign "#" and the next white space, excluding the hash "#" sign, and the string that I want to catch is alphanumeric string.

With the regex functionality provided by Javascript:
exec_result = /#(\w*)/.exec('#whatever string comes here');
I believe exec_result[1] should be the string you want.
The return value of exec() method could be found over here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

You're really close:
/^\#(\w+)\s/
The \w matches any letters or numbers (and underscores too). And the space should be outside the matching group since I guess you don't want to capture it.

To get an alphanumeric match (which will get you type1), instead of the negated character class [^\s] which matches not a whitespace character, you could use a character class and specify what you want to match like [A-Za-z0-9].
Then use a negative lookahead to assert what is on the right is not a non-whitespace char:
^#([A-Za-z0-9]+)(?!\S)
Regex demo
Your match is in the first capturing group. Note that you don't have to escape the \#
For example using the case insensitive flag /i
const regex = /^#([A-Za-z0-9]+)(?!\S)/i;
const str = `#type1 this is the text of the note`;
console.log(str.match(regex)[1]);
If you only want to match type, you might use:
^#([a-z]+)[a-z0-9]*(?!\S)
Regex demo
const regex = /^#([a-z]+)[a-z0-9]*(?!\S)/i;
const str = `#type1 this is the text of the note`;
console.log(str.match(regex)[1]);

I've figured it out.
/^\#([^\s]+)+(.*)$/

Related

Regex including all special characters except space

I have a regex which checks all the special characters except space but that looks weird and too long.
const specialCharsRegex = new RegExp(/#|#|\$|!|%|&|\^|\*|-|\+|_|=|{|}|\[|\]|\(|\)|~|`|\.|\?|\<|\>|,|\/|:|;|"|'|\\/).
This looks too long and if i use regex (\W) it also includes the space.
Is there is any way i can achieve this?
Well you could use:
[^\w ]
This matches non word characters except for space. You may blacklist anything else you also might want by adding it to the above character class.
To match anything that is not a word character nor a whitespace character (cr, lf, ff, space, tab)
const specialCharsRegex = new RegExp(/[^\w\s]+|_+/, 'g');
See this demo at regex101 or a JS replace demo at tio.run (used g flag for all occurrences)
The underscore belongs to word characters [A-Za-z0-9_] and needs to be matched separately.
Try this using a-A-0-9/a-z/A-Z
Pattern regex = Pattern.compile("[^A-Za-z0-9]");

Regex keeps finding character I want matched along with previous character

I have the following regex in javascript for a split operation since I can't do a negative look behind to find any delimiters , in a string that is not proceeded by one or more escape characters of \.
[^\\],
The regex works fine for finding where the commas not proceeded by \ are, but also finds the character that proceeds the comma as a match and thus splits the string incorrectly.
For example if I had the string
hello\,there,are
The result would be that e, matches my regex and not just ,. Making the split string array read
[hello\,ther] [are]
Why does the regex I am using keep finding the comma and the proceeding character instead of only matching the comma?
You cannot use split here because you'd need a lookbehind that JS regex does not support. Use a match with appropriate regex. Like the one below:
/(?:[^\\,]|\\.)+/g
See the regex demo.
The pattern matches 1 or more (+) sequences of any char other than , and \ ([^\\,]) or (|) any escaped character (excluding linebreak chars) with \\.
JS demo:
var regex = /(?:[^\\,]|\\.)+/g;
var str = "hello\\,there,are";
var res = str.match(regex);
console.log(res);

Javascript regex - no white space at beginning + allow space in the middle

I would like to have a regex which matches the string with NO whitespace(s) at the beginning. But the string containing whitespace(s) in the middle CAN match. So far i have tried below
[^-\s][a-zA-Z0-9-_\\s]+$
Debuggex Demo
Above is not allowing whitespace(s) at the beginning, but also not allowing in the middle/end of the string. Please help me.
In your 2nd character class, \\s will match \ and s, and not \s. Thus it doesn't matches a whitespace. You should use just \s there. Also, move the hyphen towards the end, else it will create unintentional range in character class:
^[^-\s][a-zA-Z0-9_\s-]+$
If you plan to match a string of any length (even an empty string) that matches your pattern and does not start with a whitespace, use (?!\s) right after ^:
/^(?!\s)[a-zA-Z0-9_\s-]*$/
^^^^^^
Or, bearing in mind that [A-Za-z0-9_] in JS regex is equal to \w:
/^(?!\s)[\w\s-]*$/
The (?!\s) is a negative lookahead that matches a location in string that is not immediately followed with a whitespace (matched with the \s pattern).
If you want to add more "forbidden" chars at the string start (it looks like you also disallow -) keep using the [\s-] character class in the lookahead:
/^(?![\s-])[\w\s-]*$/
To match at least 1 character, replace * with +:
/^(?![\s-])[\w\s-]+$/
See the regex demo. JS demo:
console.log(/^(?![\s-])[\w\s-]+$/.test("abc def 123 ___ -loc- "));
console.log(/^(?![\s-])[\w\s-]+$/.test(" abc def 123 ___ -loc- "));
You need to use this regex:
^[^-\s][\w\s-]+$
Use start anchor ^
No need to double escape \s
Also important is to use hyphen as the first OR last character in the character class.
\w is same as [a-zA-Z0-9_]
use \S at the beginning
^\S+[a-zA-Z0-9-_\\s]+$
This RegEx will allow neither white-space at the beginning nor at the end of. Your string/word and allows all the special characters.
^[^\s].+[^\s]$
This Regex also works Fine
^[^\s]+(\s+[^\s]+)*$
try this should work
[a-zA-Z0-9_]+.*$
/^[^.\s]/
try this instead it will not allow a user to enter character at first place
^ matches position just before the first character of the string
. matches a single character. Does not matter what character it is, except newline
\s is space
If your field for user name only accept letters and middle of space but not for begining and end
User name: /^[^\s][a-zA-Z\s]+[^\s]$/
If your field for user ID only accept letters,numbers and underscore and no spaces allow
user ID: /^[\w]+$/
If your field for password only accept letters,number and special character no spaces allow
Password: /^[\w##&]+$/
Note: \w content a-zA-Z, number, underscore (_) if you add more character, add you special character after \w.
You can compare with user ID and password field in password field im only add some special character (##&).
India public thoko like 😁
I suggest below regex for this,
^[^\s].*[^\s]$
You can try regex in here

javascript regex for special characters

I'm trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/ and which chars from .!##$%^&*()_+-= are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!##\$%\^\&*\)\(+=._-/g
but with no success
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]{6,}$/g
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so
add boolean to either match a special character or _
What's the difference?
/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/ does mean the literal sequence of those 9 characters.
Which chars from .!##$%^&*()_+-= are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.
allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!##$%\^&*)(+=._-]*$/
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Complete set of special characters:
/[\!\#\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
To answer your question:
var regular_expression = /^[A-Za-z0-9\!\#\#\$\%\^\&\*\)\(+\=\._-]+$/g
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.##]/;
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?#[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!##$%^&*])[A-Za-z\d!##$%^&*]{8,}$/
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g
You can use this to find and replace any special characters like in Worpress's slug
const regex = /[`~!##$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
This works for me in React Native:
[~_!##$%^&*()\\[\\],.?":;{}|<>=+()-\\s\\/`\'\]
Here's my reference for the list of special characters:
https://owasp.org/www-community/password-special-characters
If we need to allow only number and symbols (- and .) then we can use the following pattern
const filterParams = {
allowedCharPattern: '\\d\\-\\.', // declaring regex pattern
numberParser: text => {
return text == null ? null : parseFloat(text)
}
}

Regular expression for not allowing spaces in the input field

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/

Categories