Check for pattern match with UUIDv4 in JavaScript - javascript

I am looking for a pattern match with certain string before and after the uuid.
e.g.user/a24a6ea4-ce75-4665-a070-57453082c256/photo/a24a6ea4-ce75-4665-a070-57453082c256
const regexExp = new RegExp(/^user\/[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
console.log(regexExp.test("user/a24a6ea4-ce75-4665-a070-57453082c256")); // true
console.log(regexExp.test("user/a24a6ea4-ce75-4665-a070-57453082c256/photo")); // false
What I am expecting is to match user/{uuid}/* How to use a wildcard after the uuid?

If you want to match both, you can omit using the RegExp constructor as you are already using a literal and optionally match / followed by the rest of the string.
The [4] can be just 4
const regexExp = /^user\/[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}(?:\/.*)?$/i;
See the regex101 demo.
const regexExp = /^user\/[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}(?:\/.*)?$/i;
[
"user/a24a6ea4-ce75-4665-a070-57453082c256",
"user/a24a6ea4-ce75-4665-a070-57453082c256/photo",
"user/a24a6ea4-ce75-4665-a070-57453082c256asdasd"
].forEach(s =>
console.log(`${s} --> ${regexExp.test(s)}`)
);

Related

Regex matches numbers in date but shouldn't

Why does my regex pattern match the date part of the string? It seems like I'm not accounting for the / (slash) correctly with [^\/] to avoid the pattern to match date strings?
const reg = new RegExp(
/(USD|\$|EUR|€|USDC|USDT)?\s?(\d+[^\/]|\d{1,3}(,\d{3})*)(\.\d+)?(k|K|m|M)?\b/,
"i"
);
const str = "02/22/2021 $50k";
console.log(reg.exec(str));
// result: ['02', undefined, '02', undefined, undefined, undefined, undefined, index: 0, input: '02/22/2021 $50k', groups: undefined]
// was expecting: [$50k,...]
You get those matches for the date part and the undefined ones, because you use a pattern with optional parts and alternations |
In your pattern there is this part (\d+[^\/]|\d{1,3}(,\d{3})*). That first part of the alternation \d+[^\/] matches 1+ digits followed by any char except a / (which can also match a digit) and the minimum amount of characters is 2. That part will match 20, 22 and 2021 in the date part.
If there is 1 digit, the second part of the alternation will match it.
If you want to match only numbers as well, you can assert not / to the left and the right, and make the whole part with the first alternatives like USD optional with the optional whitspace chars as well, to prevent matching that before only digits.
The last alternation can be shortened to a character class [km]? with a case insensitive flag.
See this page for the lookbehind support for Javascript.
(?:(?:USD|\$|EUR|€|USDC|USDT)\s?)?(?<!\/)\b(?:\d{1,3}(?:,\d{3})*(?:\.\d+)?|\d+)(?!\/)[KkMm]?\b
Regex demo
const reg = /(?:(?:USD|\$|EUR|€|USDC|USDT)\s?)?(?<!\/)\b(?:\d{1,3}(?:,\d{3})*(?:\.\d+)?|\d+)(?!\/)[KkMm]?\b/gi;
const str = "02/22/2021 $50k 1,213.3 11111111 $50,000 $50000"
const res = Array.from(str.matchAll(reg), m => m[0]);
console.log(res)
If the currency is not optional:
(?:USD|\$|EUR|€|USDC|USDT)\s?(?:\d{1,3}(?:,\d{3})*(?:\.\d+)?|\d+)[KkMm]?\b
Regex demo
I can't get your regex well. so i try to figure out what result you would expect. check this. in groups you have each part of your string.
const regex = /(\d{2})*\/?(\d{2})\/(\d{2,4})?\s*(USD|\$|EUR|€|USDC|USDT)?(\d*)(k|K|m|M)?\b/i
const regexNamed = /(?<day>\d{2})*\/?(?<month>\d{2})\/(?<year>\d{2,4})?\s*(?<currency>USD|\$|EUR|€|USDC|USDT)?(?<value>\d*)(?<unit>k|K|m|M)?\b/i
const str1 = '02/22/2021 $50k'
const str2 = '02/2021 €50m'
const m1 = str1.match(regex)
const m2 = str2.match(regexNamed)
console.log(m1)
console.log(m2.groups)
Blockquote

URL regular expression pattern

I would like to parse URLs with Regular Expressions and find a pattern that matches with https://*.global.
Here is my URL test string on regex101.
Ideally, the regex would return https://app8.global instead of cover other https string.
const URL = `https://temp/"https://app8.global"https://utility.localhost/`;
const regex = /https:\/\/(.+?)\.global(\/|'|"|`)/gm;
const found = URL.match(regex);
console.log(found);
How would I manipulate the regex so it will return the https://*.global?
First of all, you need to exclude slashes from the starting part, otherwise it'll match things from the previous url:
const regex = /https:\/\/([^\/]+?)\.global(\/|'|"|`)/gm;
Now, you can convert the weird 4 character or with a character group:
const regex = /https:\/\/([^\/]+?)\.global[\/'"`]/gm;
And now you can get the matches and trim off that last character:
const matches = URL.match(regex).map(v => v.slice(0, -1));
Then, matches would evaluate to ["https://app8.global"].
Using Group RegExp.$1
const URL = `https://temp/"https://app8.global"https://utility.localhost/`;
const regex = /(https:\/\/([^\/]+?)\.global[\/'"`])/;
const found = URL.match(regex);
console.log(RegExp.$1);

Regular expression to match environment

I'm using JavaScript and I'm looking for a regex to match the placeholder "environment", which will be a different value like "production" or "development" in "real" strings.
The regex should match "environment" in both strings:
https://company-application-environment.company.local
https://application-environment.company.local
I have tried:
[^-]+$ which matches environment.company.local
\.[^-]+$ which matches .company.local
How do I get environment?
You may use this regex based on a positive lookahead:
/[^.-]+(?=\.[^-]+$)/
Details:
[^.-]+: Match 1+ of any char that is not - and .
(?=\.[^-]+$): Lookahead to assert that we have a dot and 1+ of non-hyphen characters till end.
RegEx Demo
Code:
const urls = [
"https://company-application-environment.company.local",
"https://application-environment.company.local",
"https://application-production.any.thing",
"https://foo-bar-baz-development.any.thing"
]
const regex = /[^.-]+(?=\.[^-]+$)/;
urls.forEach(url =>
console.log(url.match(regex)[0])
)
Not the fanciest reg exp, but gets the job done.
const urls = [
"https://company-application-environment.company.local",
"https://application-environment.company.local",
"https://a-b-c-d-e-f.foo.bar"
]
urls.forEach(url =>
console.log(url.match(/-([^-.]+)\./)[1])
)
As an alternative you might use URL, split on - and get the last item from the array. Then split on a dot and get the first item.
[
"https://company-application-environment.company.local",
"https://application-environment.company.local"
].forEach(s => {
let env = new URL(s).host.split('-').pop().split('.')[0];
console.log(env);
})
Match for known environments
var tests = [
'https://company-application-development.company.local',
'https://application-production.company.local',
'https://appdev.company.local',
'https://appprod.company.local'
];
tests.forEach(test => {
var pattern = /(development|dev|production|prod)/g;
var match = test.match(pattern);
console.log(`environment = ${match}`);
});
In this case, the best way to match is to literally use the word you are looking for.
And if you need to match multiple values in the environment position, use the RegEx or format. See the MDN.
(production|development)

Insure that regex moves to the second OR element only if the first one doesn't exist

I'm trying to match a certain word on a string and only if it doesn't exist i want to match the another one using the OR | operator ....but the match is ignoring that... how can i insure that the behavior works :
const str = 'Soraka is an ambulance 911'
const regex = RegExp('('+'911'+'|'+'soraka'+')','i')
console.log(str.match(regex)[0]) // should get 911 instead
911 occurs late in the string, whereas Soraka occurs earlier, and the regex engine iterates character-by-character, so Soraka gets matched first, even though it's on the right-hand side of the alternation.
One option would be to match Soraka or 911 in captured lookaheads instead, and then with the regex match object, alternate between the two groups to get the one which is not undefined:
const check = (str) => {
const regex = /^(?=.*(911)|.*(Soraka))/;
const match = str.match(regex);
console.log(match[1] || match[2]);
};
check('Soraka is an ambulance 911');
check('foo 911');
check('foo Soraka');
You can use includes and find
You can pass the strings in the priority sequence, so as soon as find found any string in the original string it returns that strings back,
const str = 'Soraka is an ambulance 911'
const findStr = (...arg) => {
return [...arg].find(toCheck => str.includes(toCheck))
}
console.log(findStr("911", "Soraka"))
You can extend the findStr if you want your match to be case insensitive something like this
const str = 'Soraka is an ambulance 911'
const findStr = (...arg) => {
return [...arg].find(toCheck => str.toLowerCase().includes(toCheck.toLowerCase()))
}
console.log(findStr("Soraka", "911"))
If you want match to be whole word not the partial words than you can build dynamic regex and use it search value
const str = '911234 Soraka is an ambulance 911'
const findStr = (...arg) => {
return [...arg].find(toCheck =>{
let regex = new RegExp(`\\b${toCheck}\\b`,'i')
return regex.test(str)
})
}
console.log(findStr("911", "Soraka"))
Just use a greedy dot before a capturing group that matches 911 or Soraka:
/.*(911)|(Soraka)/
See the regex demo
The .* (or, if there are line breaks, use /.*(911)|(Soraka)/s in Chrome/Node, or /[^]*(911)|(Soraka)/ to support legacy EMCMScript versions) will ensure the regex index advances to the rightmost position when matching 911 or Soraka.
JS demo (borrowed from #CertainPerformance's answer):
const check = (str) => {
const regex = /.*(911)|(Soraka)/;
const match = str.match(regex) || ["","NO MATCH","NO MATCH"];
console.log(match[1] || match[2]);
};
check('Soraka is an ambulance 911');
check('Ambulance 911, Soraka');
check('foo 911');
check('foo Soraka');
check('foo oops!');

Manipulate a string containing a file's path to get only the file name

I got a file path as
falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540hherax%252Fiia-mas-app-new//IIAMASATTCHMENTS/BD6FE729-70F1-48B0-83EB-8E7D956E599E.MOV
as file extension will change as file type
file path will also change
how could I manipulate string to get file name as
BD6FE729-70F1-48B0-83EB-8E7D956E599E"
is in given example
2nd example of path and file type change
falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540ppphrx%252Fiia-mas-app-new//IIAMASATTCHMENTS/DD6FE729-60F2-58B0-8M8B-8E759R6E547K.jpeg
you can do simply
let str="falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540hherax%252Fiia-mas-app-new//IIAMASATTCHMENTS/BD6FE729-70F1-48B0-83EB-8E7D956E599E.MOV"
console.log( str.split(".")[0].split("/").pop()
)
just remember split split pop
Some variation of slice/split would work
const str = 'falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540hherax%252Fiia-mas-app-new//IIAMASATTCHMENTS/BD6FE729-70F1-48B0-83EB-8E7D956E599E.MOV'
console.log(
str.slice(str.lastIndexOf("/")+1).split(".")[0]
)
// or
console.log(
str.split("/").pop().split(".")[0]
)
You can use regular expression for example.
The first thing comes in my mind is:
const filepath = 'falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540hherax%252Fiia-mas-app-new//IIAMASATTCHMENTS/BD6FE729-70F1-48B0-83EB-8E7D956E599E.MOV'
const filenameWithoutExtension = filepath.match(/IIAMASATTCHMENTS\/(.*)\./)[1] // "BD6FE729-70F1-48B0-83EB-8E7D956E599E"
console.log(filenameWithoutExtension)
If you know the format of the value you want to capture, you might get a more exact match using a regex and capture your value in the first capturing group.
You might use the /i flag to make the match case insensitive.
([A-Z0-9]+(?:-[A-Z0-9]+){4})\.\w+$
That will match:
( Capturing group
[A-Z0-9]+ Match 1+ times what is listed in the character class
(?:-[A-Z0-9]+){4} Repeat 4 times matching a hyphen and 1+ times what is listed in the character class
) Close capturing group
\.\w+$ Match a dot, 1+ times a word char and assert the end of the string
Regex demo
let strs = [
`falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540hherax%252Fiia-mas-app-new//IIAMASATTCHMENTS/BD6FE729-70F1-48B0-83EB-8E7D956E599E.MOV`,
`falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540ppphrx%252Fiia-mas-app-new//IIAMASATTCHMENTS/DD6FE729-60F2-58B0-8M8B-8E759R6E547K.jpeg`
];
let pattern = /([A-Z0-9]+(?:-[A-Z0-9]+){4})\.\w+$/i;
strs.forEach(str => console.log(str.match(pattern)[1]));
You could use regular expressions like here:
function get_filename(str) {
const regex = /\/([A-Z0-9\-_]+)\.[\w\d]+/gm;
let m = regex.exec(str);
return m[1];
}
console.log(
get_filename(`falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540ppphrx%252Fiia-mas-app-new//IIAMASATTCHMENTS/DD6FE729-60F2-58B0-8M8B-8E759R6E547K.jpeg`)
)
var filpath = "falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540hherax%252Fiia-mas-app-new//IIAMASATTCHMENTS/BD6FE729-70F1-48B0-83EB-8E7D956E599E.MOV"
console.log(
filpath.substring(filpath.lastIndexOf('/') + 1, filpath.length).substring(1, filpath.substring(filpath.lastIndexOf('/') + 1, filpath.length).lastIndexOf('.'))
)
var str = "falsefile:///var/mobile/Containers/Data/Application/D4B6F6CD-5E5C-4459-90CC-0C649B3B31B8/Documents/ExponentExperienceData/%2540hherax%252Fiia-mas-app-new//IIAMASATTCHMENTS/BD6FE729-70F1-48B0-83EB-8E7D956E599E.MOV",
re = /[\w|-]*\.\w*/
stringNameWithExt = str.match(re)
stringNameWithoutExt = str.match(re)[0].split(".")[0]
console.log(stringNameWithoutExt)

Categories

Resources