objectron | generic model to test equality | Regex library
kandi X-RAY | objectron Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
objectron Key Features
objectron Examples and Code Snippets
Trending Discussions on Regex
Trending Discussions on Regex
QUESTION
I have the following regex: /\.([s]?[ac]ss)$/
. The problem is, it matches .scss
, .sass
, .css
, .ass
. How would I make it not match .ass
?
ANSWER
Answered 2022-Mar-02 at 08:35You can use
\.(?!a)(s?[ac]ss)$
See the regex demo. Details:
\.
- a dot(?!a)
- the next char cannot bea
(s?[ac]ss)
- Group 1: an optionals
,a
orc
and thenss
$
- end of string.
Another regex that can work is
\.(s(?:css|ass)|css)$
See this regex demo. Details:
\.
- a dot(s(?:css|ass)|css)
-s
and thencss
orass
orcss
$
- end of string.
NOTE: if you have a dynamic, user-defined list of such fixed strings to match after a .
at the end of string, you can build these regexes automatically using the code at the bottom of my answer.
QUESTION
I have an array of 5 numbers, I'd like to match as long as there are three of the same number and two of the same different number in the array, placement does not matter. Number sequences can be any random string of 5 numbers between 1 - 5. Examples of matches would be: 33322
24422
52225
44111
54545
*basically any grouping of 2 and 3 of the same numbers needs to match.
Best I've come up with so far: ^([0-9])\1{2}|([0-9])\1{1}$
I am not so good with regex, any help would be greatly appreciated.
ANSWER
Answered 2022-Jan-16 at 23:38You can use
^(?=[1-5]{5}$)(?=.*(\d)(?:.*\1){2})(?=.*(?!\1)(\d).*\2)\d+$
^(?=.*(\d)(?:.*\1){2})(?=.*(?!\1)(\d).*\2)[1-5]{5}$
See the regex demo.
If you want to allow any digits, replace [1-5]
with \d
.
Details:
^
- start of string(?=[1-5]{5}$)
- there must be five digits from1
to5
till end of string (this lookahead makes non-matching strings fail quicker)(?=.*(\d)(?:.*\1){2})
- a positive lookahead that requires any zero or more chars as many as possible, followed with a digit (captured into Group 1) and then two sequences of any zero or more chars as many as possible and the same digit as captured into Group 1 immediately to the right of the current location(?=.*(?!\1)(\d).*\2)
- a positive lookahead that requires any zero or more chars as many as possible, followed with a digit (captured into Group 2) that is not equal to the digit in Group 1, and then any zero or more chars as many as possible and the same digit as captured into Group 2 immediately to the right of the current location\d+
- one or more digits$
- end of string.
QUESTION
Currently, this is my code.
function clean_string(raw_string) {
A =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890".split(
""
);
var cleaned_string = raw_string.toLowerCase();
for (i = 0; i < cleaned_string.length; i++) {
if (!A.includes(cleaned_string[i])) {
cleaned_string = setCharAt(cleaned_string, i, " ");
}
}
cleaned_string = cleaned_string.replace(/\s\s+/g, " ");
return cleaned_string;
}
function setCharAt(str, index, chr) {
if (index > str.length - 1) return str;
return str.substring(0, index) + chr + str.substring(index + 1);
}
I don't know regex and it'll probably be easier with regex. Here's what I want to do:
Input: Hello, David World 123!
Output: hello david world 123
.
Input: hELlo., <>;dAVId world .;- 123
Output: hello david world 123
.
Input: He.llo David, w!orld 123#
Output: he llo david w orld 123
.
Basically what I want to do is replace anything but a-z0-9 with a space and then remove double spaces. In other words, I only want a-z0-9 in my results. How can I do that?
P.S. The code works but I think it looks bad and pretty inefficient.
EDIT: Sorry, I meant I only want lowercase letters in my output. I'm dumb.
ANSWER
Answered 2022-Jan-06 at 04:57A simple solution would be to convert all characters to lowercase, replace any character that isn't a-z, 0-9, or a space with a space character, and then replace multiple space characters with a single space character.
function sanitize(input) {
return input
.toLowerCase()
.replace(/([^a-z\d\s]+)/g, ' ')
.replace(/(\s+)/g, ' ');
}
console.log(sanitize('Hello, David World 123!'));
console.log(sanitize('hELlo., <>;dAVId world .;- 123'));
console.log(sanitize('He.llo David, w!orld 123#'));
QUESTION
I am generating some meaningful name with the following rule in a JavaScript/Node JS program:
Input: "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"
Expected output: "TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId"
Rules:
- replace any character with zero or more underscore to the non-underscored uppercase Example:
x | __*x => X
- If exists remove last _
This is what is tried so far, looking for better alternatives, if any:
const convertBetterString = (input) => {
const finalString = [];
if (input && input.includes('_')) {
const inputStringSeparation = input.split('_');
if (inputStringSeparation.length > 1) {
if (inputStringSeparation[inputStringSeparation.length - 1] === '') {
inputStringSeparation.splice(inputStringSeparation.length - 1, 1);
}
inputStringSeparation.forEach((val, index) => {
if (val === '' && inputStringSeparation[index + 1]) {
const actualString = inputStringSeparation[index + 1];
const formattedString = actualString.charAt(0).toUpperCase() + actualString.slice(1);
finalString.push(formattedString);
}
});
return finalString.length > 0 ? finalString.join('') : inputStringSeparation.join('');
} else {
return input.charAt(0).toUpperCase() + input.slice(1);
}
} else {
return input;
}
}
ANSWER
Answered 2021-Dec-17 at 14:21Split and slice
const capitalise = str => str.slice(0,1).toUpperCase() + str.slice(1); // you can add more tests
const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"
const newStr = str.split(/_+/)
.map(word => capitalise(word))
.join("")
console.log(newStr)
Regexp with optional chaining
const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId_"
const newStr = str.replace(/(?:_+|^)(\w)?/g, (_,letter) => letter?.toUpperCase() ?? "")
console.log(newStr)
Explanation
(?:_+|^)
non-capturing the underscore OR start
(\w)?
followed by 0 or 1 letter to be captured
(_,letter) => letter?.toUpperCase() ?? "")
ignore the match and uppercase the letter if found, that ignores trailing underscores too
QUESTION
Java 11 added some new methods to the Pattern
class (a compiled version of a regular expression), including:
I am trying to understand the difference between the two and when I would want to use one over the other?
ANSWER
Answered 2021-Nov-16 at 14:57Pattern.asPredicate
will return true if any part of the input string matches the Regular expression. You should use this method if you're testing some larger body of text for a certain pattern. For example, to test whether a comment from a user contains a hyperlink.Pattern.asMatchPredicate
will return true if the entire input string matches the Regular expression. You should use this method if you're testing the entire input for a certain pattern. For example, to validate the phone number of a user in their profile.
Pattern.asPredicate
internally uses Matcher.find()
, while Pattern.asMatchPrediate
internally uses Matcher.matches()
. So the difference between the two boils down to the difference between these two methods from the Matcher
class.
Below are some examples to showcase the difference. You can copy & paste below code in an online Java sandbox like https://www.compilejava.net/ to play around with it yourself.
import java.util.regex.Pattern;
import java.util.function.Predicate;
public class main
{
public static void main(String[] args) {
Pattern pattern = Pattern.compile("abc");
// asPredicate will match any part of the input string
Predicate asPredicate = pattern.asPredicate();
// True, because abc is part of abc
System.out.printf("asPredicate: abc: %s\n", asPredicate.test("abc"));
// True, because abc is part of abcabc
System.out.printf("asPredicate: abcabc: %s\n", asPredicate.test("abcabc"));
// True, because abc is part of 123abc123
System.out.printf("asPredicate: 123abc123: %s\n", asPredicate.test("123abc123"));
// False, because abc is NOT part of 123
System.out.printf("asPredicate: 123: %s\n", asPredicate.test("123")); // -> false
// asMatchPredicate will only match the entire input string
Predicate asMatchPredicate = pattern.asMatchPredicate();
// True, because abc exactly matches abc
System.out.printf("asMatchPredicate: abc: %s\n", asMatchPredicate.test("abc"));
// False, because abc does not exactly match abcabc
System.out.printf("asMatchPredicate: abcabc: %s\n", asMatchPredicate.test("abcabc"));
// False, because abc does not exactly match 123abc123
System.out.printf("asMatchPredicate: 123abc123: %s\n", asMatchPredicate.test("123abc123"));
// False, because abc does not exactly match 123
System.out.printf("asMatchPredicate: 123: %s\n", asMatchPredicate.test("123"));
}
}
QUESTION
I am trying to replace a single occurrence of a character '1' in a String with a different character.
This same character can occur multiple times in the String which I am not interested in.
For example, in the below string I want to replace the single occurrence of 1 with 2.
input:-0001011101
output:-0002011102
I tried the below regex but it is giving be wrong results
regex b1("(1){1}");
S1=regex_replace( S,
b1, "2");
Any help would be greatly appreciated.
ANSWER
Answered 2021-Nov-13 at 09:22Use a negative lookahead in the regexp to match a 1
that isn't followed by another 1
:
regex b1("1(?!1)");
QUESTION
I'm attempting to solve a very simple problem - find strings in an array which only contain certain letters. However, I've run up against something in the behavior of regular expressions and/or grep
that I don't get.
#!/usr/bin/perl
use warnings;
use strict;
my @test_data = qw(ant bee cat dodo elephant frog giraffe horse);
# Words wanted include these letters only. Hardcoded for demonstration purposes
my @wanted_letters = qw/a c d i n o t/;
# Subtract those letters from the alphabet to find the letters to eliminate.
# Interpolate array into a negated bracketed character class, positive grep
# against a list of the lowercase alphabet: fine, gets befghjklmpqrsuvwxyz.
my @unwanted_letters = grep(/[^@wanted_letters]/, ('a' .. 'z'));
# The desired result can be simulated by hardcoding the unwanted letters into a
# bracketed character class then doing a negative grep: matches ant, cat, and dodo.
my @works = grep(!/[befghjklmpqrsuvwxyz]/, @test_data);
# Doing something similar but moving the negation into the bracketed character
# class fails and matches everything.
my @fails1 = grep(/[^befghjklmpqrsuvwxyz]/, @test_data);
# Doing the same thing that produced the array of unwanted letters also fails.
my @fails2 = grep(/[^@unwanted_letters]/, @test_data);
print join ' ', @works; print "\n";
print join ' ', @fails1; print "\n";
print join ' ', @fails2; print "\n";
Questions:
- Why does
@works
get the correct result but not@fails1
? Thegrep
docs suggest the former, and the negation section ofperlrecharclass
suggests the latter, although it uses=~
in its example. Is this something specifically to do with usinggrep
? - Why does
@fails2
not work? Is it something to do with array vs list context? It otherwise looks the same as the subtraction step. - Besides that, is there a pure regex way to achieve this that avoids the subtraction step?
ANSWER
Answered 2021-Nov-02 at 13:15Both fails
are fixed with the addition of anchors ^
and $
and quantifier +
These both work:
my @fails1 = grep(/^[^befghjklmpqrsuvwxyz]+$/, @test_data);
my @fails2 = grep(/^[^@unwanted_letters]+$/, @test_data);
Keep in mind that /[^befghjklmpqrsuvwxyz]/
or /[^@unwanted_letters]/
only matches ONE character. Adding +
means as many as possible. Adding ^
and $
means all characters from the start to the end of the string.
With /[@wanted_letters]/
you will return a match if there is a single wanted character (even with unwanted characters in the string) -- the logical equivalent to any. Compare to /^[@wanted_letters]+$/
where all the letters need to be in the set of @wanted_letters
and is the equivalent of all.
Demo1 only ONE character so grep
fails.
Demo2 quantifier means more than one but no anchor - grep fails
Demo3 Anchors and quantifier - expected result.
Once you understand character classes only match ONE character and anchors for the WHOLE string and quantifiers for everything extending the match to the anchors, you can directly grep just with wanted letters:
my @wanted = grep(/^[@wanted_letters]+$/, @test_data);
QUESTION
I'm looking for a regexp that matches any line that contains 'B', 'R', 'A' and 'S' (in any order) at the start. It would match all the following lines, except the last two.
BRASIL
BSRAIL
BARSILERO
BRASILERA
BRASILEÑA
BRASILEÑO
BARBADOS
BOSNIA AND HERZEGOVINA
I tried the following:
^(B|R|A|S){4}.*$
^(?=.*B)(?=.*R)(?=.*A)(?=.*S).*$
^(?=.{4})(?=.*B)(?=.*R)(?=.*A)(?=.*S).*$
^(?=.*B)(?=.*R)(?=.*A)(?=.*S){4}.*$
^(?=.*B){1}(?=.*R){1}(?=.*A){1}(?=.*S){1}.*$
ANSWER
Answered 2021-Oct-30 at 21:05There are only 24 permutations :)
^(ABRS|BARS|RABS|ARBS|BRAS|RBAS|RBSA|BRSA|SRBA|RSBA|BSRA|SBRA|SARB|ASRB|RSAB|SRAB|ARSB|RASB|BASR|ABSR|SBAR|BSAR|ASBR|SABR)
You can shorten it a bit by grouping pairs of two:
^((AB|BA)(RS|SR)|(AR|RA)(BS|SB)|(AS|SA)(BR|RB)|(BR|RB)(AS|SA)|(BS|SB)(AR|RA)|(RS|SR)(AB|BA))
Each double pair matches 4 inputs, e.g., (AB|BA)(RS|SR)
can match:
ABRS
ABSR
BARS
BASR
QUESTION
I have a Json file having multiple comments and I want to replace a value in it.
I tried the below and it gives me a json file without comments. But I don't understand how to change the value and save it back with comments. Is this even possible because we are replacing all the comments with empty lines?
$json = Get-Content $jsonfile -Raw | ConvertFrom-Json
$configfile = $json -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/'
My config.json is as below and I want to change the value of "version" to 10 through a powershell script and then save it back with the comments intact.
{
"FramewokSettings": {
"Name": "VX",
"Version": "8", // The value here is not constant. It can be something like v1.4.56.456 also
"GitVersion": "v5",
"DatabaseVersion": "7",
// Doing xyz
"CounterVersion": "2"
// Doing ABC.
// Start
}
}
ANSWER
Answered 2021-Oct-22 at 22:32Use
(Get-Content test.txt) -replace '^(\s*"Version"\s*:\s*")[^"]*', '${1}10' | Set-Content test.txt
See proof.
EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to $1:
--------------------------------------------------------------------------------
\s* whitespace (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
"Version" '"Version"'
--------------------------------------------------------------------------------
\s* whitespace (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
\s* whitespace (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
) end of $1
--------------------------------------------------------------------------------
[^"]* any character except: '"' (0 or more times
(matching the most amount possible))
QUESTION
The header question may not be easy to understand. Hope you can understand my detailed info below.
I have sentence data below, that has some tags, represented by [tn]tag[/tn]
:
const sentence = `[t1]Sometimes[/t1] that's [t2]just the way[/t2] it has to be. Sure, there
were [t3]probably[/t3] other options, but he didn't let them [t4]enter his mind[/t4]. It
was done and that was that. It was just the way [t5]it[/t5] had to be.`
And i have parts of the sentence.
const parts = [
"Sometimes that's just the way",
"it has to be",
"Sure,",
"there were probably other options,",
"but he didn't let them enter his mind.",
"It was done and that was that.",
"It was just the way it had to be."
];
Goal is to add tags on each parts using the sentence above.
const expectedOutput = [
"[t1]Sometimes[/t1] that's [t2]just the way[/t2]",
"it has to be",
"Sure,",
"there were [t3]probably[/t3] other options,",
"but he didn't let them [t4]enter his mind[/t4].",
"It was done and that was that.",
"It was just the way [t5]it[/t5] had to be."
];
What I've tried so far are the following, but seemingly does not make sense, and I endup nothing.
- make a clone sentence, and remove all tags. (code below)
- find all parts in the sentence.
- [problem is I don't know how to put again the tags]
I wanna ask is there any chance to achieve it? and how. thanks
export const removeTags = (content) => {
content = content.replace(/([t]|[\/t])/g, '');
return content.replace(/([t\d+]|[\/t\d+])/g, '');
};
ANSWER
Answered 2021-Oct-04 at 08:47Here is a solution that assumes that there are no nested tags, that all tags open and close in the part. Also, this assumes that all characters from the sentence are in parts
. For this last assumption, I had to add the .
after it has to be in the second expected part. I also had to remove newline characters from the sentence but I think it was because of the copy/paste. This solution will loop through all characters and store two parallel buffers : one with the tags, one without. We will use the second one to compare with the parts, and use the first one to generate the output.
const sentence = `[t1]Sometimes[/t1] that's [t2]just the way[/t2] it has to be. Sure, there were [t3]probably[/t3] other options, but he didn't let them [t4]enter his mind[/t4]. It was done and that was that. It was just the way [t5]it[/t5] had to be.`
const parts = [
"Sometimes that's just the way",
"it has to be.",
"Sure,",
"there were probably other options,",
"but he didn't let them enter his mind.",
"It was done and that was that.",
"It was just the way it had to be."
];
let bufferWithoutTags = ""
let bufferWithTags = ""
const output = []
const buffers = []
let tagOpened = false
for (let i = 0; i < sentence.length; ++i) {
let c = sentence[i]
bufferWithTags += c
if ( c === '[') {
if (tagOpened && sentence[i+1] === "/") {
tagOpened = false
} else {
tagOpened = true
}
while (c != ']') {
c = sentence[++i]
bufferWithTags += c
}
} else {
bufferWithoutTags += c;
}
if (!tagOpened) {
for (const part of parts) {
if (part === bufferWithoutTags.trim()) {
output.push(bufferWithTags.trim())
bufferWithTags = bufferWithoutTags = ""
}
}
}
}
console.log(output)
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install objectron
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page