Answer the question
In order to leave comments, you need to log in
Help with regex to test string like 159.5|15|19.6 and pull numbers
Good afternoon everyone! I have been suffering for about half an hour, and I can not solve the problem.
There is a line like 159.5|15|19.6
Requirements:
- The number of numbers can be any
- The fractional part of the number can be separated by either a dot or a comma.
— The string must not contain the symbol "|" at the beginning and at the end (i.e. must begin and end with numbers)
— The string must not contain any extra characters
I got the following expression, which correctly finds all numbers:
(?<=^|\d\|)(\d+(?:[\.,]\d)?)+(?=\|\d|$)
But when I try to insert the characters of the beginning or end of the string ^ and $ , I get nothing. I do like this:
^((?<=^|\d\|)(\d+(?:[\.,]\d)?)+(?=\|\d|$))+
but in this case, the expression finds only the first number, and does not pay attention to the rest. Accordingly, it is clear that if you enter the $ symbol at the end of the line , then nothing will be found at all.
I tried a bunch of different options, but I will not litter the question with them. I know I'm misunderstanding something about grouping, but what? Tell me please
Answer the question
In order to leave comments, you need to log in
This cannot be done for fundamental reasons.
In your expression:
(?<=^|\d\|)(\d+(?:[\.,]\d)?)+(?=\|\d|$)
it turns out not one match, but three matches of an integer expression per line - so you see each group with numbers separately, as an array. ^(?:(\d+(?:[\.,]\d+)?)(?:\|)?)+
here all three numbers came under the group, but the last of them was preserved there as a value. the repeated capturing group will capture only the last iteration
$ echo -e "23561|783242|4823948.423847|47828374\n159,5|15|19.6\n253f|fjdk|fd32"| \
sed -r 's/^([0-9]+([,.][0-9]+){0,1}\|)+[0-9]+([,.][0-9]+){0,1}$/hi__&__bye/'
hi__23561|783242|4823948.423847|47828374__bye
hi__159,5|15|19.6__bye
253f|fjdk|fd32
I would do like this:
while ($s =~ s/([\d,.]+)//) {
print "$1\n";
}
^(?:\d+[,\.]?\d*\|)*(?:\d+[,\.]?\d*)+$
I had to duplicate the template for finding the number, but I don't see another way.
I doubt that this problem will have a solution with a simple regexp, in general.
If you specify in advance the number of ' | ' then you can, or use 2 options: split + (\d+)[,.](\d+)-for each of the split-tokens.
I get two regexps. And for both tasks I can’t reduce them (pseudo javascript)
The task is to get numbers:
var my_regexp = /(?:\||^)(\d+(?:[.,]?\d+)?)(?=\||$)/gi;
var my_str = "159,5|15|19.6|16|199,55|56.7";
var my_nums = [];
var ar;
while( (ar = my_regexp.exec(my_str)) != null )
{
my_nums.push(ar[1]);
}
alert(my_nums);
var my_regexp = /^(?:(?:\||^)(\d+(?:[.,]?\d+)?)(?=\||$))+$/gi;
var my_str = "159,5|15|19.6|16|199,55|56.7";
alert(my_regexp.test(my_str));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question