Match by regular expression to string replace by JavaScript - javascript

My string is like
5blog5sett5ings5[5slider5][5][5ima5ge5]
I like to match any digit into second brackets from end by regular expression.
For this case, my target digit is 5 into [5].
I like to select where before pattern like
5blog5sett5ings5[5slider5][ and after pattern like ][5ima5ge5]
I will use it for JavaScript string replace. Text can be different but the before and after patterns are like that. For better understanding see the image.
I tried something like
(?<=.+[.+?][)\d(?=][.+?])
but did not work.

I think you could just use a lookahead to check if there ] and one more [ ] ahead until end.
\d+(?=]\[[^\]]*]$)
See demo at regex101
(be aware that lookbehind you tried is not available in js regex)

I guess you can use:
\[(\d+)\][^\]]+]$
Regex Demo & Explanation
var myString = "5blog5sett5ings5[5slider5][5][5ima5ge5]";
var myRegexp = /\[(\d+)\][^\]]+]$/mg;
var match = myRegexp.exec(myString);
console.log(match[1]);

Use this:
^.*\[(\d*)\]\[[^\]]*\]$
Where:
^ is the begin of the string
.* means any character
\[ and \] matches literal squared brackets
(\d*) is what you want to match
[^\]]* is the content of the last couple of brackets
$ is the end of the string
See an example:
var str = "5blog5sett5ings5[5slider5][5][5ima5ge5]";
var res = str.match(/^.*\[(\d*)\]\[[^\]]*\]$/);
console.log(res[1])

Related

how to found 2 matches in regular expression

I need a regular expression for :
<<12.txt>> <<45.txt>
I have created a regular expression :
<<.+.txt>>
But this found one match in whole string but here is 2 matches:
<<12.txt>>
<<45.txt>>
if anyone have solution for this problem please help me out there
Part of the issue is that the string you've specified wouldn't match because the second > is missing in <<45.txt>.
Also, you're using the . (dot) selector, and also trying to find a period. It works, but now how you think it is.
Here's the regex you want:
var regex = /<<\d+\.txt>>/g
\d matches only numbers
\. matches an actual period
/g means global, so it won't stop at the first match
Practice Regular Expressions
https://regexr.com/43bs4
Demo
var string = "<<12.txt>> <<45.txt>>";
var regex = /<<\d+\.txt>>/g;
var matches = string.match(regex);
console.log(matches);
P.S., if you actually want to match with 1 > or 2 >>, you can with:
var regex = /<<\d+\.txt>>?/g
? optionally matches the character right before it
/<<.+.txt>>/gm
g is for global (will search through entire source)
m is for multi line search support

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

Javascript Regex to match standalone S without matching apostrophe S

I am trying to match a stand alone s ignoring case. I do not want to match an s that is preceded by an apostrophe. My current regex is /\b[s]\b/ig and my test string is and the S on lines 2 and 3 should be the only matches.
Men's
S
Just S Things
Somethings
Regexr: http://regexr.com/3geo2
After a short experimentation I have came up with the following regex
(?:\s|^)s(?:\s|$)
DEMO
One trick you could use is to use alternation between a non-capturing and a capturing expression, and then in your post-processing of the regex matches, discard the matches that don't have a capture group.
The regex would be:
/'s|(\bs\b)/ig
And if you were using it to do replacement operations, it would be used like:
var str = "Men's\nS\nJust S Things\nSomethings";
var updatedStr = str.replace(/'s|(\bs\b)/ig,
(match, captureGroup) => captureGroup ? "<S>" : match
);
console.log(updatedStr);

Javascript string split with regex

I am trying to split a string using a regular expression for links (urls).
The regex in question is
var regex = new RegExp('(?:^(?:(?:[a-z]+:)?//)(?:\S+(?::\S*)?#)?(?:localhost|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$)')
If i do
regex.test("https://google.com"); // returns true
but doing -
"Go to https://google.com".split(regex);
// return ["Go to https://google.com"]
Whereas i expect it to return
["Go to ", "https://google.com"]
Any idea what's going on here?
First of all, you're using a string literal to build your regex, which means that you have to escape your backslashes (since a backslash has a special meaning in strings, used for the line feed char \n for example):
var regex = new RegExp('(?:^(?:(?:[a-z]+:)?//)(?:\\S+(?::\\S*)?#)?(?:localhost|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:[/?#]\\S*)?$)');
Another solution would be to use the regex literal, as JavaScript proposes one, but you would then have to escape the slashes:
var regex = /(?:^(?:(?:[a-z]+:)?\/\/)(?:\S+(?::\S*)?#)?(?:localhost|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[\/?#]\S*)?$)/;
Then, your regex will try to match against the entire input due to the ^ and $ anchors. So if you remove them (or better, replace them with word boundaries \b), you'll be able to find URLs in a string for example:
var regex = /(?:\b(?:(?:[a-z]+:)?\/\/)(?:\S+(?::\S*)?#)?(?:localhost|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[\/?#]\S*)?\b)/;
But, the main point is that you're misunderstanding the split concept. Given the string "hello world", if you split by space, you'll end up with ["hello", "world"]: no more space anymore since it was the char that was used to split.
That is, if you split by the URL regex, the output array won't contain the URLs anymore. It seems to me that a lookahead could suit your needs:
var regex = /(?=(?:\b(?:(?:[a-z]+:)?\/\/)(?:\S+(?::\S*)?#)?(?:localhost|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[\/?#]\S*)?\b))/;
"Go to https://google.com".split(regex) // ["Go to ", "https://google.com"]
The regex explained:
(?=(?:\b(?:(?:[a-z]+:)?//)(?:\S+(?::\S*)?#)?(?:localhost|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?\b))
Debuggex Demo
By splitting a string with a positive lookahead (?=content_of_lookahead), you'll split by each interchar that is followed by the content of the lookahead.
Take a look at 8 Regular Expressions You Should Know.
To match an url you can use following regex :
var regex = "(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w# \.-]*)*\/?$";
"Go to https://google.com".split(regex);
// return ["https://google.com"]
Live example.
Hope this helps.

Regular expression giving incorrect output

I am using regex to verify that a string only contains alphabets and spaces. Regex is defined as
var regex = /^[A-Za-z ]/;
but even if I am testing it with a string "X," , it is giving a true result.
What is the error here?
^[A-Za-z ] only matches one character. and ^ means the start of the string. To accomplish what you want, use:
+ - This means match one or more. Alternatively you can use:
* - Which means match zero or more.
But I think you're better off with the first one (+). Another thing is, match for the whole string. This means you have to search from the first to the last character.
$ - This means match the end.
Your code should be like this:
var regex = /^[A-Za-z ]+$/;
Your regex matches the first letter of your input and therefore true is returned.. You need to add $ to make sure you only match a complete string from the beginning (^) to the end ($).
var regex = /^[A-Za-z ]*$/;
Try using this:
/^[a-zA-Z\ ]+$/
This is the correct way:
/^[A-Za-z ]*$/
Regex Demo

Categories

Resources