How to add symbol in regular expression by condition? - regex

I need to add 0 if a founded number is less than 10 in the regular expression:
My expressions:
searching string:
"createdAt":\s+\[\s+([0-9]+),\s+([0-9]+),\s+([0-9]+),\s+([0-9]+),\s+([0-9]+),\s+([0-9]+)\s+]
replacing:
"createdAt": "($1)-($2)-($3)T($4):($5):($6)"
Result:
Input data:
"createdAt": [
2022,
4,
15,
13,
43,
7
]
Expected output data:
"createdAt":"2022-04-15T13:43:07"
Actual output data (4 except 04 and 7 except 07):
"createdAt":"2022-4-15T13:43:7"
--
So, how to add conditions in this case?

If you're ok with manipulating the array:
const json = {
"createdAt": [
2022,
4,
15,
13,
43,
7
]
}
const formattedJson = json.createdAt.map((n) => n.toString().padStart(2, 0))
console.log(formattedJson);
Or using regex on the date string:
const date = "2022-4-15T13:43:7"
const formattedDate = date.replace(/\b(\d)\b/g, '0$1')
console.log(formattedDate);
Breakdown of /\b(\d)\b/g
\b - Word boundary. In this case we're wrapping a boundary around any single digit.
\d - Any digit 0-9
() - Capturing group. This allows us to reference anything between the parentheses at a later point.
This is the replacement '0$1'. The $1 is how we reference the capturing group. If we had multiple capturing groups, we'd reference the second one with $2, the third with $3, etc..
In this case we're just saying - look for any single digit and replace it with a 0 and the digit itself.

Related

Regex expression to check if contains more than 2 repeated characters

I am checking in my validation form if there are repeated more than two times the same character.
I have tried this expression ([a-zA-Z0-9])\1{2,} but it doesn't work properly because if I add aaA it founds the string and it shouldn't because "aaA" is permitted. Also it doesn't check if it is repeated a special character.
Here is how I applied my code:
this.form = this.formBuilder.group(
{
newpassword: new FormControl(
'',
Validators.compose([
Validators.required,
CustomValidators.patternValidator(/[(\[a-zA-Z0-9\])\\1{2,}]/, {
hasRepeatedCharacters: true,
}),
])
),
},
{ validators: this.password }
);
Any idea?
If I understand correctly what you are considering to be invalid, you want this:
/(.)\1{2,}/
Use the following regex to detect any character repeated 2 or more times:
(.)\1{2,}
In order to capture aaA (repeated letters irrespective of their case) as well, you'll need to add the case-insensitive i flag.
You can use /(.)(?=\1.*\1)/, assuming you allow the repeated characters to be non-consecutive:
const pat = /(.)(?=.*\1.*\1)/;
[
"a",
"aa",
"aaa",
"zba1a1za",
"aaA",
"aaAA",
"aAaAa",
"aAbbAb",
].forEach(e => console.log(`'${e}' => ${pat.test(e)}`));

How to find any non-digit characters using RegEx in ABAP

I need a Regular Expression to check whether a value contains any other characters than digits between 0 and 9.
I also want to check the length of the value.
The RegEx I´ve made: ^([0-9]\d{6})$
My test value is: 123Z45 and 123456
The ABAP code:
FIND ALL OCCURENCES OF REGEX '^([0-9]\d{6})$' IN L_VALUE RESULTS DATA(LT_RESULTS).
I´m expecting a result in LT_RESULTS, when I´m testing the first test value '123Z45', because there is a non-digit character.
But LT_RESULTS is in nearly every test case empty.
Your expression ^([0-9]\d{6})$ translates to:
^ - start of input
( - begin capture group
[0-9] - a character between 0 and 9
\d{6} - six digits (digit = character between 0 and 9)
) - end capture group
$ - end of input
So it will only match 1234567 (7 digit strings), not 123456, or 123Z45.
If you just need to find a string that contains non digits you could use the following instead: ^\d*[^\d]+\d*$
* - previous element may occur zero, one or more times
[^\d] - ^ right after [ means "NOT", i.e. any character which is not a digit
+ - previous element may occur one or more times
Example:
const expression = /^\d*[^\d]+\d*$/;
const inputs = ['123Z45', '123456', 'abc', 'a21345', '1234f', '142345'];
console.log(inputs.filter(i => expression.test(i)));
You can also use this character class if you want to extract non-digit group:
DATA(l_guid) = '0074162D8EAA549794A4EF38D9553990680B89A1'.
DATA(regx) = '[[:alpha:]]+'.
DATA(substr) = match( val = l_guid
regex = regx
occ = 1 ).
It finds a first occured non-digit group of characters and shows it.
If you want to just check if they are exists or how much of them reside in your string, count built-in function is your friend:
DATA(how_many) = count( val = l_guid regex = regx ).
DATA(yes) = boolc( count( val = l_guid regex = regx ) > 0 ).
Match and count exist since ABAP 7.50.
If you don't need a Regular Expression for something more complex, ABAP has some nice comparison operators CO (Contains Only), CA, NA etc for you. Something like:
IF L_VALUE CO '0123456789' AND STRLEN( L_VALUE ) = 6.

error while applying regex to numeric values to replace values in nifi

hi I have a data as below
[{
s1 = 98493456645
s2 = 0000000000
102 = 93234,
12 =
15 = rahdeshfui
16 = 2343432,234234
},
{
s1 = 435234235
s2 = 01
102 = 45336
12 =
15 = vjsfrh#gmail.com
16 = 2415454
}
]
now using reg expression i need to change to json format and i have tried this
regexp:- ([^\s]+?.*)=((.*(?=,$))+|.*).*
replace value:- "$1":"$2",
for this values i am getting output as below
[{
"s1":"98493456645",
"s2":"0000000000",
"102":"93234,",
"12":"",
"15":"rahdeshfui",
"16":"2343432,234234",
},
{
"s1":"435234235",
"s2":"01",
"102":"45336",
"12":"",
"15":"vjsfrh#gmail.com",
"16":"2415454"
}
]
but I my expected output should be as below
[{
"s1":98493456645,
"s2":0,
"102":93234,
"12":"",
"15":"rahdeshfui",
"16":"2343432,234234",
},
{
"s1":435234235,
"s2":01,
"102":45336,
"12":"",
"15":"vjsfrh#gmail.com",
"16":"2415454"
}
]
for numneric numbers their should not be in "" and if i have a value more than one 0 i need to replace it with single 0 and for some values i have , at end i need to skip , in case if i have one
It might be a bit cumbersome, but you want to replace multiple things so one option might be to use multiple replacements.
Note that these patterns do not take the opening [{ and closing ]] into account or any nesting but only the key value part as your posting pattern is for the example data.
1.) Wrap the keys and values in double quotes while not capturing the
comma at the end and match the equals sign including the surrounding
spaces:
(\S+) = (\S*?),?(?=\n) and replace with "$1":"$2",
Demo
2.) Remove the double quotes around the digits except for those that start with 0:
("[^"]+":)"(?!0+[1-9])(\d+)"" and replace with $1$2
Demo
3.) Remove the comma after the last key value:
("[^"]+":)(\S+),(?!\n *"\w+") and replace with $1$2
Demo
4.) Replace 2 or more times a zero with a single zero:
("[^"]+":)0{2,} and replace with $10
Demo
That will result in:
[{
"s1":98493456645,
"s2":0,
"102":93234,
"12":"",
"15":"rahdeshfui",
"16":"2343432,234234"
},
{
"s1":435234235,
"s2":"01",
"102":45336,
"12":"",
"15":"vjsfrh#gmail.com",
"16":2415454
}
]
Is assume the last value "16":"2415454" is "16":2415454 as the value contains digits only.

Filter a string using regular expression

I tried the following code. However, the result is not what I want.
$strLine = "100.11 Q9"
$sortString = StringRegExp ($strLine,'([0-9\.]{1,7})', $STR_REGEXPARRAYMATCH)
MsgBox(0, "", $sortString[0],2)
The output shows 100.11, but I want 100.11 9. How could I display it this way using a regular expression?
$sPattern = "([0-9\.]+)\sQ(\d+)"
$strLine = "100.11 Q9"
$sortString = StringRegExpReplace($strLine, $sPattern, '\1 \2')
MsgBox(0, "$sortString", $sortString, 2)
$strLine = "100.11 Q9"
$sortString = StringRegExp($strLine, $sPattern, 3); array of global matches.
For $i1 = 0 To UBound($sortString) -1
MsgBox(0, "$sortString[" & $i1 & "]", $sortString[$i1], 2)
Next
The pattern is to get the 2 groups being 100.11 and 9.
The pattern will 1st match the group with any digit and dot until it reach
/s which will match the space. It will then match the Q. The 2nd group
matches any remaining digits.
StringRegExpReplace replaces the whole string with 1st and 2nd groups
separated with a space.
StringRegExp get the 2 groups as 2 array elements.
Choose 1 from the 2 types regexp above of which you prefer.

Can this be done with regex?

I have a string with different length sub-strings split by symbol '_' and some sub-strings have to be split in multiple sub-sub-strings...
Example:
"_foo-2_bar-12_un[3;1]iver[3]se[3-7]"
should be split in groups like this:
"foo-2", "2", "bar-12", "12", "un[3;1]", "3;1", "iv", "er[3]", "3", "se[3-7]", "3-7"
I've come up with something like this:
/(?:((?:(?:\[([a-z0-9;-]+)\])|(?<=_)(?:[a-z0-9]+)|-([0-9]+))+))/ig
The problem I encounter is with the last part. And after finicking around I started to think whether or not this is even possible. Is it?
Any kind of a guidance is appreciated.
You can use the following regex:
/[^\W_]+(?:\[([^\][]*)]|-([^_]+))/g
See the regex demo
The pattern matches any 1+ char alphanumeric sequence ([^\W_]+) followed either with [...] substrings having no [ and ] inside (with \[([^\][]*)] - note it captures what is inside [...] into Group 1) OR a hyphen followed with 1+ characters other than _ (and this part after - is captured into Group 2).
var re = /[^\W_]+(?:\[([^\][]*)]|-([^_]+))/g;
var str = '_foo-2_bar-12_un[3;1]iver[3]se[3-7]';
var res = [];
while ((m = re.exec(str)) !== null) {
res.push(m[0]);
if (m[1]) {
res.push(m[1]);
} else {
res.push(m[2]);
}
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";
In this code, the match object is analyzed at each iteration: the 0th group (the whole match) ias added to the final array, and then if Group 1 matched, Group 1 is added, else, Group 2 is added to the resulting array.