How to javascript regex match the following? - javascript

I only want to match ones that say:
Given I string, I want something that is able to detect words that match anything with the following pattern of "TERMINATE:" + any number of random letters or numbers:
"VIRUS:XPA"
"VIRUS:IDI"
Then the function should return "true" to indicate there is only a virus.
But if the string is the following:
"ANM|SDO|FSD:SOS|VIRUS:XPA"
"ANM:SOS|SDO|FSD:SOS|VIRUS:XLS"
"VIRUS:XLS|ANM:SOS|SDO|FSD:SOS|VIRUS:XPL"
"VIRUS:XLS|ANM:SOS"
Then the function should return "false" to indicate there is no virus, or the virus is masked.
Can this be done with a single regular expression in javacsript?

You mean something like this ?
var isVirus = /^VIRUS\:\w*$/.test(str)

Related

How to write regexp for finding :smile: in javascript?

I want to write a regular expression, in JavaScript, for finding the string starting and ending with :.
For example "hello :smile: :sleeping:" from this string I need to find the strings which are starting and ending with the : characters. I tried the expression below, but it didn't work:
^:.*\:$
My guess is that you not only want to find the string, but also replace it. For that you should look at using a capture in the regexp combined with a replacement function.
const emojiPattern = /:(\w+):/g
function replaceEmojiTags(text) {
return text.replace(emojiPattern, function (tag, emotion) {
// The emotion will be the captured word between your tags,
// so either "sleep" or "sleeping" in your example
//
// In this function you would take that emotion and return
// whatever you want based on the input parameter and the
// whole tag would be replaced
//
// As an example, let's say you had a bunch of GIF images
// for the different emotions:
return '<img src="/img/emoji/' + emotion + '.gif" />';
});
}
With that code you could then run your function on any input string and replace the tags to get the HTML for the actual images in them. As in your example:
replaceEmojiTags('hello :smile: :sleeping:')
// 'hello <img src="/img/emoji/smile.gif" /> <img src="/img/emoji/sleeping.gif" />'
EDIT: To support hyphens within the emotion, as in "big-smile", the pattern needs to be changed since it is only looking for word characters. For this there is probably also a restriction such that the hyphen must join two words so that it shouldn't accept "-big-smile" or "big-smile-". For that you need to change the pattern to:
const emojiPattern = /:(\w+(-\w+)*):/g
That pattern is looking for any word that is then followed by zero or more instances of a hyphen followed by a word. It would match any of the following: "smile", "big-smile", "big-smile-bigger".
The ^ and $ are anchors (start and end respectively). These cause your regex to explicitly match an entire string which starts with : has anything between it and ends with :.
If you want to match characters within a string you can remove the anchors.
Your * indicates zero or more so you'll be matching :: as well. It'll be better to change this to + which means one or more. In fact if you're just looking for text you may want to use a range [a-z0-9] with a case insensitive modifier.
If we put it all together we'll have regex like this /:([a-z0-9]+):/gmi
match a string beginning with : with any alphanumeric character one or more times ending in : with the modifiers g globally, m multi-line and i case insensitive for things like :FacePalm:.
Using it in JavaScript we can end up with:
var mytext = 'Hello :smile: and jolly :wave:';
var matches = mytext.match(/:([a-z0-9]+):/gmi);
// matches = [':smile:', ':wave:'];
You'll have an array with each match found.

TS/JS split part of a string from regex match

In the past, I had this regex:
\{(.*?)\}
And entered this string:
logs/{thing:hi}/{thing:hello}
Then I used the following:
console.log(string.split(regex).filter((_, i) => i % 2 === 1));
To get this result:
thing:hi
thing:hello
For irrelevant design reasons, I changed my regex to:
\{.*?\}
But now, when using the same test string and split command, it returns only this:
/
I want it to return this:
{thing:hi}
{thing:hello}
How can I modify the split (or anything else) to do this?
Why not use match?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
The match() method retrieves the matches when matching a string against a regular expression.
If you're only interested in returning the two string matches then it's much simpler than using split.
var foo = "logs/{thing:hi}/{thing:hello}";
console.log(foo.match(/{.*?}/g));

Does a string contain a price?

I'd like to check whether or not a string such as "The computer costs $2,000" contains a price or not.
I slightly modified this regex to fit my needs and the current regex that I am using looks like this:
var regexTest = /(?=.)^\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/;
If I do regexTest.test("$2,000"); it will return true. However, if I add additional characters to the string such as regexTest.test("The computer costs $2,000"); it will return false.
How should I modify the regex code in order to return true for the second example?
remove your ^ in regex. try this one
Also I recommend to remove $ as well so price like this $5.000,00 words will return true
var regexTest = /(?=.)\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?/;
console.log(regexTest.test('computer $5,000.00'));
console.log(regexTest.test('$5,000.00'));
console.log(regexTest.test('$5,000.00 that was computer price'));
console.log(regexTest.test('computer 5,000.00'));
The global modifier should work. Add the g after the last /
var regexTest = /(?=.)^\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/g;
Should match with all instances inside the test string.

Add text after a special character

I have a string which is punctuated and I would like to add   after all symbols.
For example, this string:
Hi there, how are you ? Ok/not_ok !
I expect it to become like this:
Hi there,  how are you ?  Ok/ not_ ok ! 
I was thinking about the replace function, but I'll need to call it lot of times for all symbols...
str.replace("/","/ ");
str.replace(",",", ");
str.replace("!","! ");
str.replace("?","? ");
str.replace("_","_ ");
Is there an easier way to achieve this using only 1 function? I was thinking about regexp, something similar to this:
str.replace([/,!?_],<selection>+" ");
Use capturing group based regex. This would capture the special characters into a group. Later we could refer those captured characters by specifying the group index number along with the $ symbol in the replacement part (like $1, $2).
var s = "Hi there, how are you ? Ok/not_ok !"
alert(s.replace(/([\/,!?_])/g, "$1 "))

How to match 'aA1' or 'Aa1' or '1aA' with regex?

I have a text box and want to match the pattern as
[a-z]{1}[A-Z]{1}[0-9]{1}
var x=/^[a-z]{1}[A-Z]{1}[0-9]{1}$/;
if(!x.test(document.getElementById('name').value))
{
alert("enter the correct format");
return false;
}
It works only for the value : aA1
what to do if
these values can be entered randomly
like aA1, Aa1, 1aA ?
To match a set of strings in any order you can use lookahead. Something like this:
/^(?=.*a)(?=.*b)(?=.*c)[abc]{3}$/.test('cab')
The syntax (?=whatever) is a positive lookahead, meaning it checks for a match without advancing the position of matcher. So each group looks for your characters anywhere in the string. The last part [abc]{3} ensures that no other characters are present in the string, and that there are exactly three characters. If multiples are okay, use [abc]+ instead.
For a more detailed reference see http://www.regular-expressions.info/lookaround.html.
You can use the monster expression
/$([a-z][A-Z][0-9])|([A-Z][a-z][0-9])|([0-9][a-z][A-Z])|([a-z][0-9][A-Z])|([A-Z][0-9][a-z])|([0-9][A-Z][a-z])^/
but I'm not sure this is an efficient or scalable solution.
Try this
/^([a-z]{1}[A-Z]{1}[0-9]{1}|[A-Z]{1}[a-z]{1}[0-9]{1}|[0-9]{1}[a-z]{1}[A-Z]{1})$/
The First expression [a-z]{1}[A-Z]{1}[0-9]{1} deals with the pattern : aA1
The Second epression [A-Z]{1}[a-z]{1}[0-9]{1} deals with the pattern : Aa1
And the Third expression [0-9]{1}[a-z]{1}[A-Z]{1} deals with the pattern : 1aA

Categories