Regex - to extract text before the last a hyphen/dash - javascript

Example data expected output
sds-rwewr-dddd-cash0-bbb cash0
rrse-cash1-nonre cash1
loan-snk-cash2-ssdd cash2
garb-cash3-dfgfd cash3
loan-unwan-cash4-something cash4
The common pattern is here, need to extract a few chars before the last hyphen of given string.
var regex1= /.*(?=(?:-[^-]*){1}$)/g ; //output will be "ds-rwewr-dddd-cash0" from "sds-rwewr-dddd-cash0-bbb "
var regex2 = /\w[^-]*$/g ; //output will be "cash0" from "ds-rwewr-dddd-cash0"
var res =regex2.exec(regex1.exec(sds-rwewr-dddd-cash0-bbb)) //output will cash0
Although above nested regex is working as expected but may not be optimize one. So any help will be appreciated for optimized regex

You can use
/\w+(?=-[^-]*$)/
If the part before the last hyphen can contain chars other than word chars, keep using \w[^-]*: /\w[^-]*(?=-[^-]*$)/. If you do not need to check the first char of your match, simply use /[^-]+(?=-[^-]*$)/.
See the regex demo.
Details:
\w+ - one or more word chars
(?=-[^-]*$) - that must be followed with - and then zero or more chars other than - till the end of string.
JavaScript demo
const texts = ['sds-rwewr-dddd-cash0-bbb','rrse-cash1-nonre','loan-snk-cash2-ssdd','garb-cash3-dfgfd','loan-unwan-cash4-something'];
const regex = /\w+(?=-[^-]*$)/;
for (var text of texts) {
console.log(text, '=>', text.match(regex)?.[0]);
}

Related

How to remove specific letters using regex in javascript

var cartstring = "27,00 - R"
How can I remove spaces and "-" and "R" using only regex (not allowed to use slice etc.)? I need to make strings cartstring1 and cartstring2 which should both be equal to "27,00", first by removing spaces and "-" and "R", and second by allowing only numbers and ",".
cartstring1 = cartstring.replace(/\s/g, "");
cartstring2 = cartstring.replace(/\D/g, "");
Please help me modify these regular expressions to have a working code. I tried to read about regex but still cannot quite get it. Thank you very much in advance.
you can just capture just what you are interested in number and comma:
let re = /[\d,]+/g
let result = "27,00 - R".match(re)
console.log(result)
You can group the characters you want to remove:
var cartstring = "27,00 - R"
let res = cartstring.replace(/(\s|-|R)/g, "")
console.log(res)
Or alternatively, split the string by a space and get the first item:
var cartstring = "27,00 - R"
let res = cartstring.split(" ")[0]
console.log(res)
You are using 2 replacements, one replacing all whitespace chars \s and the other replacing all non digits \D, but note that \D also matches \s so you could omit the first call.
Using \D will also remove the comma that you want to keep, so you can match all chars except digits or a comma using [^\d,]+ in a single replacement instead:
var cartstring = "27,00 - R";
console.log(cartstring.replace(/[^\d,]+/g, ''));

Is it possible to have one regex that solves this task?

string = '1,23'
When a comma is present in the string, I want the regex to match the first digit (\n) after the comma e.g.2.
Sometimes the comma will not be there. When it's not present, I want the regex to match the first digit of the string e.g. 1.
Also, we can't reverse the order of the string to solve this task.
I am genuinely stuck. The only idea I had was prepending this: [,|nothing]. I tried '' to mean nothing but that didn't work.
You can match an optional sequence of chars other than a comma and then a comma at the start of a string, and then match and capture the digit with
/^(?:[^,]*,)?(\d)/
See the regex demo.
Details
^ - start of string
(?:[^,]*,)? - an optional sequence of
[^,]* - 0 any chars other than a comma
, - a comma
(\d) - Capturing group 1: any digit
See the JavaScript demo:
const strs = ['123', '1,23'];
const rx = /^(?:[^,]*,)?(\d)/;
for (const s of strs) {
const result = (s.match(rx) || ['',''])[1];
// Or, const result = s.match(rx)?.[1] || "";
console.log(s, '=>', result);
}

Javascript Regex: Capture between two asterisks with multiple asterisks in comma delimited string

I am trying to capture all characters between multiple instances of asterisks, which are comma delimited in a string. Here's an example of the string:
checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*
The caveat is that the phrase must start and end with an asterisk. I have been able to come close by using the following regex, however, it won't discard any matches when the captured string is missing the starting asterisk(*):
let str = "checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*"
const regex = /[^\,\*]+(?=\*)/gi;
var a = str.match(regex)
console.log(a) // answer should exclude checkboxID0 and checkboxID5
The answer returns the following, however, "checkboxID0 and checkboxID5" should be excluded as it doesn't start with an asterisk.
[
"checkboxID0",
"checkboxID1",
"checkboxID3",
"checkboxID5"
]
Thanks, in advance!
You need to use asterisks on both ends of the pattern and capture all 1 or more chars other than commas and asterisks in between:
/\*([^,*]+)\*/g
See the regex demo
Pattern details
\* - an asterisk
([^,*]+) - Capturing group 1: one or more chars other than , and *
\* - an asterisk
JS demo:
var regex = /\*([^,*]+)\*/g;
var str = "checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*";
var m, res = [];
while (m = regex.exec(str)) {
res.push(m[1]);
}
console.log(res);

Get the string between the last 2 / in regex in javascript

How can I get the strings between last 2 slashes in regex in javascript?
for example:
stackoverflow.com/questions/ask/index.html => "ask"
http://regexr.com/foo.html?q=bar => "regexr.com"
https://www.w3schools.com/icons/default.asp => "icons"
You can use /\/([^/]+)\/[^/]*$/; [^/]*$ matches everything after the last slash, \/([^/]+)\/ matches the last two slashes, then you can capture what is in between and extract it:
var samples = ["stackoverflow.com/questions/ask/index.html",
"http://regexr.com/foo.html?q=bar",
"https://www.w3schools.com/icons/default.asp"]
console.log(
samples.map(s => s.match(/\/([^/]+)\/[^/]*$/)[1])
)
You can solve this by using split().
let a = 'stackoverflow.com/questions/ask/index.html';
let b = 'http://regexr.com/foo.html?q=bar';
let c = 'https://www.w3schools.com/icons/default.asp';
a = a.split('/')
b = b.split('/')
c = c.split('/')
indexing after split()
console.log(a[a.length-2])
console.log(b[b.length-2])
console.log(c[c.length-2])
I personally do not recommend using regex. Because it is hard to maintain
I believe that will do:
[^\/]+(?=\/[^\/]*$)
[^\/]+ This matches all chars other than /. Putting this (?=\/[^\/]*$) in the sequence looks for the pattern that comes before the last /.
var urls = [
"stackoverflow.com/questions/ask/index.html",
"http://regexr.com/foo.html?q=bar",
"https://www.w3schools.com/icons/default.asp"
];
urls.forEach(url => console.log(url.match(/[^\/]+(?=\/[^\/]*$)/)[0]));
You can use (?=[^/]*\/[^/]*$)(.*?)(?=\/[^/]*$). You can test it here: https://www.regexpal.com/
The format of the regex is: (positive lookahead for second last slash)(.*?)(positive lookahead for last slash).
The (.*?) is a lazy match for what's between the slashes.
references:
Replace second to last "/" character in URL with a '#'
RegEx that will match the last occurrence of dot in a string

Get all words starting with X and ending with Y

I have got a textarea with keyup=validate()
I need a javascript function that gets all words starting with # and ending with a character that is not A-Za-z0-9
For example:
This is a text #user1 this is more text #user2. And this is even more #user3!
The function gives an array:
Array("#user1","#user2","#user3");
I am sure there must be a way to do this written on somewhere on the internet if I just google something but I have no idea what I have to look for.. I am very new with regular expresions.
Thank you very much!
The regular expression you want is:
/#[a-z\d]+/ig
This matches # followed by a sequence of letters and numbers. The i modifier makes it case-insensitive, so you don't have to put A-Z in the character class, and g makes it find all the matches.
var str = "This is a text #user1 this is more text #user2. And this is even more #user3!";
var matches = str.match(/#[a-z\d]+/ig);
console.log(matches);
JS
var str = "This is a text #user1 this is more text #user2. And this is even more #user3!",
var textArr = str.split(" ");
for(var i = 0; i < textArr.length; i++) {
var test = textArr[i];
matches = test.match(/^#.*.[A-Za-z0-9]$/);
console.log(matches);
};
Explanation:
You should also read about the regex(http://www.w3schools.com/jsref/jsref_obj_regexp.asp) and match(http://www.w3schools.com/jsref/jsref_match.asp) to get an idea how it works.
Basically, applying ^# means starting the regex look for #. $ means ending with. and .* any character in between.
To Test: http://www.regular-expressions.info/javascriptexample.html
Thanks for the replies above, they've helped me - Where I've written this method that hopefully answers the question about having a start and end regex check.
In this example it looks for ##_ at the start and _## at the end
e.g. ##_ anyTokenYouNeedToFind _##.
Code:
const tokenSearchHelper = (inputText) => {
let matches = inputText.match(/##_[a-zA-Z0-9_\d]+_##/ig);
return matches;
}
const out = tokenSearchHelper("Hello ##_World_##");
console.log(out);

Categories