Regular expression to extract words from string - regex

I have a string as
str= "value 1 then perform certain action"
I need a regular expression that will make sure value and perform are present in string without being repeated.

no need regular expression for this simple task. use this code
str= "value 1 then perform certain action"
var a = str.match("value") || []
var b = str.match("perform") || []
if(a.length == 1 && b.length == 1){
console.log("true")
}else{
console.log("false")
}

You can set the pattern as follows:
pattern: "value (.*) perform (.*)"

Related

How to check is Jenkins pram contains a character

I am trying to check if my Jenkins parameter contains a hostname.
But when I use Regular Expressions to see if it contains the name it doesn't check.
I would guess I have an error in the way I am checking or how I have it wrapped in brackets.
Below is a sample of what I am working with
stage('Release 1') {
when {
expression { params.SECRET_NAME != "" && params.STAGING_ENV != ("*some.host.name*") }
}
steps {
echo "Release 1"
}
}
stage('Release 2') {
when {
expression {params.STAGING_ENV == ("*some.host.name*") && params.SECRET_NAME == ("*+*") }
}
steps {
echo "Release 2"
}
}
}
I want it to skip the stage in my Jenkins pipeline if it does not meet the conditions
Ok, you need multiple changes here, from inside out:
Replace the * with .*. Simply put, in regex * denotes the same (set) of characters any number of times (abc* matches abccccc), whereas .* denotes any character any number of times (abc.* matches abccccc, abcdefg, abcadkhsdalksd, etc.).
Remove the double quotes " surrounding the regex patterns; lest you want them to be interpreted as string literals.
Wrap the regex patterns within delimiters, usually / to define the string boundary.
The brackets () themselves are optional here.
To match regular expressions, replace the equal operator == with the match operator ==~ (strict), which returns a boolean.
There is no "NOT match" operator in Groovy. To invert the match, you need to invert the result of the entire expression.
If the + in *+*should be a literal, then you must escape it as *\+*.
Stitching these together, your pipeline should look like:
stage('Release 1') {
when {
expression {
params.SECRET_NAME != "" && !(params.STAGING_ENV ==~ /.*some.host.name.*/)
}
}
steps {
echo "Release 1"
}
}
stage('Release 2') {
when {
expression {
params.STAGING_ENV ==~ /.*some.host.name.*/ && params.SECRET_NAME ==~ /.*\+.*/
}
}
steps {
echo "Release 2"
}
}
Further reading:
http://docs.groovy-lang.org/latest/html/documentation/core-operators.html
http://web.mit.edu/hackl/www/lab/turkshop/slides/regex-cheatsheet.pdf

Another regex expression

I need a regular expression for the next rules:
should not start or end with a space
should contain just letters (lower / upper), digits, #, single quotes, hyphens and spaces (spaces just inside, but not at the beginning and the end, as I already said)
should contain at least one letter (lower or upper).
Thank you
I think
^[^ ](?=.*[a-zA-Z]+)[a-zA-Z0-9#'\- ]*[^ ]$
should help you.
"Does it really matter guys?"
with regards to the dialect of regex: yes it does matter. Different languages may have different dialects. One example off the top of my head is that the RegEx library in PHP supports lookbehinds whereas RegEx library in JavaScript does not. This is why it is important for you to list the underlying language that you're using. Also for future reference, it is helpful for those wanting to answer your questions to provide us with sample input and sample matches from the input.
Using the information that you provided, this is also a question that I feel as though you should use RegEx and JavaScript to validate the input. Take a look at this example:
window.onload = function() {
var valid = "a1 - 'super' 1";
var invalid1 = " a1 - 'super' 1"; //leading ws
var invalid2 = "a1 - 'super' 1 "; //trailing ws
var invalid3 = "a1 - 'super' 1?"; //invalid (?) char
var invalid4 = "1 - '123'"; //no letters
console.log(valid + ": " + validation(valid));
console.log(invalid1 + ": " + validation(invalid1));
console.log(invalid2 + ": " + validation(invalid2));
console.log(invalid3 + ": " + validation(invalid3));
}
function validation(input) {
var acceptableChars = new RegExp(/[^a-zA-Z\d\s'-]/g);
var containsLetter = new RegExp(/[a-zA-Z]/);
return input.length > 1 && input.trim().length == input.length && !acceptableChars.test(input) && containsLetter.test(input);
}

Regex: Any letters, digit, and 0 up to 3 special chars

It seems I'm stuck with a simple regex for a password check.
What I'd like:
8 up to 30 symbols (Total)
With any of these: [A-Za-z\d]
And 0 up to 3 of these: [ -/:-#[-`{-~À-ÿ] (Special list)
I took a look here and then I wrote something like:
(?=.{8,15}$)(?=.*[A-Za-z\d])(?!([ -\/:-#[-`{-~À-ÿ])\1{4}).*
But it doesn't work, one can put more than 3 of the special chars list.
Any tips?
After shuffling your regex around a bit, it works for the examples you provided (I think you made a mistake with the example "A#~` C:", it should not match as it has 6 special chars):
(?!.*(?:[ -\/:-#[-`{-~À-ÿ].*){4})^[A-Za-z\d -\/:-#[-`{-~À-ÿ]{8,30}$
It only needs one lookahead instead of two, because the length and character set check can be done without lookahead: ^[A-Za-z\d -/:-#[-`{-~À-ÿ]{8,30}$
I changed the negative lookahead a bit to be correct. Your mistake was to only check for consecutive special chars, and you inserted the wildcards .* in a way that made the lookahead never hit (because the wildcard allowed everything).
Will this work?
string characters = " -/:-#[-`{-~À-ÿ";
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string[] inputs = {
"AABBCCDD",
"aaaaaaaa",
"11111111",
"a1a1a1a1",
"AA####AA",
"A1C EKFE",
"AADE F"
};
foreach (string input in inputs)
{
var counts = input.Cast<char>().Select(x => new { ch = characters.Contains(x.ToString()) ? 1 : 0, letter = letters.Contains(x.ToString()) ? 1 : 0, notmatch = (characters + letters).Contains(x) ? 0 : 1}).ToArray();
Boolean isMatch = (input.Length >= 8) && (input.Length <= 30) && (counts.Sum(x => x.notmatch) == 0) && (counts.Sum(x => x.ch) <= 3);
Console.WriteLine("Input : '{0}', Matches : '{1}'", input, isMatch ? "Match" : "No Match");
}
Console.ReadLine();
I would use: (if you want to stick to Regex)
var specialChars = #" -\/:-#[-`{-~À-ÿ";
var regularChars = #"A-Za-z\d";
if (Regex.Match(password,$"^(.[{regularChars}{specialChars}]{7,29})$").Success && Regex.Matches(password, $"[{specialChars}]").Count<=3))
{
//Password OK
}
If consists of:
Check Length and if password contains illegal characters
Check if ony contains 3 times special char
A litle faster:
var specialChars = #" -\/:-#[-`{-~À-ÿ";
var regularChars = #"A-Za-z\d";
var minChars = 8;
var maxChars = 30;
if (password.Length >= minChars && password.Length <= maxChars && Regex.Match(password,$"^[{regularChars}{specialChars}]+$").Success && Regex.Matches(password, $"[{specialChars}]").Count<=3))
{
//Password OK
}
Newbie here..I think I've managed to get what you need but one of the test cases you shared was kinda weird..
A#~` C:
OK -- Match (3 specials, it's okay)
Shouldn't this be failed because it has more than 3 specials?
Could you perhaps try this? If it works I'll type out the explanations for the regex.
https://regex101.com/r/KCL6R1/2
(?=^[A-Za-z\d -\/:-#[-`{-~À-ÿ]{8,30}$)^(?:[A-Za-z\d]*[ -\/:-#[-`{-~À-ÿ]){0,3}[A-Za-z\d]*$

Jmeter- Concatenate multiple results returned fro regular expression extractor

I have a regex that produce multiple matches and then i wanna to concatenate all result by comma separator ?
How can i do that ?
Here is the regex:
Regx : data-rk="([^"]+)
template : $1$
Match no. : -1
I wanna the variable to have the value as :1,2,3
Note: when am using g modifier at the end of the regex no data is returned.
Below is the code for to get array of regular expression data
int count = Integer.parseInt(vars.get("value_matchNr"));
String delimiter = ",";
StringBuffer sb = new StringBuffer();
for(int i=1;i<=count;i++) {
sb.append(vars.get("value_" + i));
if (i == count){
break; //to eliminate comma after the array
}else {
sb.append(delimiter);
}
}
vars.put("arrayOutPut",sb.toString());
System.out.println(sb.toString());
Request :
Regular expression:
Response out:

I want to check a string against many different regular expressions at once

I have a string which the user has inputted and I have my regular expressions within my Database and I can check the input string against those regular expressions within the database fine.
But now I need to add another column within my database which will hold another regular expression but I want to use the same for loop to check the input string againt my new regular expression aswell but at the end of my first loop. But I want to use this new expression against the same string
i.e
\\D\\W\\D <-- first expression
\\d <-- second expression which I want to use after the first expression is over
use regular expressions from database against input string which works
add new regular expression and corporate that within the same loop and check against the same string - not workin
my code is as follows
std::string errorMessages [2][2] = {
{
"Correct .R\n",
},
{
"Free text characters out of bounds\n",
}
};
for(int i = 0; i < el.size(); i++)
{
if(el[i].substr(0,3) == ".R/")
{
DCS_LOG_DEBUG("--------------- Validating .R/ ---------------");
output.push_back("\n--------------- Validating .R/ ---------------\n");
str = el[i].substr(3);
split(st,str,boost::is_any_of("/"));
DCS_LOG_DEBUG("main loop done");
for (int split_id = 0 ; split_id < splitMask.size() ; split_id++ )
{
boost::regex const string_matcher_id(splitMask[split_id]);
if(boost::regex_match(st[split_id],string_matcher_id))
{
a = errorMessages[0][split_id];
DCS_LOG_DEBUG("" << a );
}
else
{
a = errorMessages[1][split_id];
DCS_LOG_DEBUG("" << a);
}
output.push_back(a);
}
DCS_LOG_DEBUG("Out of the loop 2");
}
}
How can I retrieve my regular expression from the database and after this loops has finished use this new regex against the same string.
STRING IS - shamari
regular expresssion i want to add - "\\d"
ask me any questions if you do not understand
I'm not sure I understand you entirely, but if you're asking "How do I combine two separate regexes into a single regex", then you need to do
combinedRegex = "(?:" + firstRegex + ")|(?:" + secondRegex + ")"
if you want an "or" comparison (either one of the parts must match).
For an "and" comparison it's a bit more complicated, depending on whether these regexes match the entire string or only a substring.
Be aware that if the second regex uses numbered backreferences, this won't work since the indexes will change: (\w+)\1 and (\d+)\1 would have to become (?:(\w+)\1)|(?:(\d+)\2), for example.