how to convert in time format with regex in dart - regex

I have a String [1: 3] who can be also [24: 59].
I have no problem with [24: 59] but I tried to convert [1: 3] to 01:03 currently I use regex to extract 1 and 3 with this code
RegExp regExp = new RegExp(
r"(\d+), (\d+)",
);
var match = regExp.firstMatch(rappel1);
group1rappel1 = match.group(1);
group2rappel1 = match.group(2);
prefs.setString('counter700',"$group1rappel1:$group2rappel1");
the result is 1:3, I don't know how to add decimal.

void main() {
final regExp = RegExp(r'\[\s*(\d{1,2})\:\s*(\d{1,2})\]');
final match1 = regExp.firstMatch('[1: 3]');
print(match1.group(1).padLeft(2, '0'));
print(match1.group(2).padLeft(2, '0'));
final match2 = regExp.firstMatch('[24: 59]');
print(regExp.hasMatch('[24: 59]'));
print(match2.group(1).padLeft(2, '0'));
print(match2.group(2).padLeft(2, '0'));
}
If you want to support more than 2 digits you can use \d+ instead of \d{1,2} (or \d{1,5})

Related

How to match sequences of consecutive Date like characters string in Dart?

I have consecutive characters as date like 20210215 and 14032020
I am trying to convert to date string like 2021.02.15 and 14.03.2020
My first problem is the consecutive characters it is in 2 format type. Like:
1) 20210215
2) 14032020
And my second problem to convert them to date string without changing the format. Like:
1) 2021.02.15
2) 14.03.2020
When I search about regex couldn't find any pattern to convert the above {20210215} consecutive characters examples to date {2021.02.15} string.
What is correct regex pattern to convert both format as I describe above in Dart?
UPDATE-1:
I need to turn this string "20210215" to this "2021.02.15" as a string and not DateTime. Also I need to turn this string "14032020" to this string "14.03.2020". And I don't want to turn to DateTime string.
First I need to detected if the year is in beginning of the string or end of it. Than put dot (.) between the day, month and year string.
UPDATE-2:
this is best I can found but it turns 02 day or month to 2. But I need as it is.
var timestampString = '13022020';//'20200213';
var re1 = RegExp(
r'^'
r'(?<year>\d{4})'
r'(?<month>\d{2})'
r'(?<day>\d{2})'
r'$',
);
var re2 = RegExp(
r'^'
r'(?<day>\d{2})'
r'(?<month>\d{2})'
r'(?<year>\d{4})'
r'$',
);
var dateTime;
var match1 = re1.firstMatch(timestampString);
if (match1 == null) {
var match2 = re2.firstMatch(timestampString);
if (match2 == null) {
//throw FormatException('Unrecognized timestamp format');
dateTime = '00.00.0000';
print('DATE_TIME: $dateTime');
} else {
var _day = int.parse(match2.namedGroup('day'));
var _month = int.parse(match2.namedGroup('month'));
var _year = int.parse(match2.namedGroup('year'));
dateTime = '$_day.$_month.$_year';
print('DATE_TIME(match2): $dateTime');
}
} else {
var _year = int.parse(match1.namedGroup('year'));
var _month = int.parse(match1.namedGroup('month'));
var _day = int.parse(match1.namedGroup('day'));
dateTime = '$_year.$_month.$_day';
print('DATE_TIME(match1): $dateTime');
}
Output:
DATE_TIME: 2020.2.13
But I need to get output as 2020.02.13.
Second is match1 also prints 1302.20.20 But if I remove var match2 section and if format is like 20200213 it works but doesn't print the 0 as I post it above.
You can use
text.replaceAllMapped(RegExp(r'\b(?:((?:19|20)\d{2})(0?[1-9]|1[0-2])(0?[1-9]|[12][0-9]|3[01])|(0?[1-9]|[12][0-9]|3[01])(0?[1-9]|1[0-2])((?:19|20)\d{2}))\b'), (Match m) => m[4] == null ? "${m[1]}.${m[2]}.${m[3]}" : "${m[4]}.${m[5]}.${m[6]}")
The \b(?:((?:19|20)\d{2})(0?[1-9]|1[0-2])(0?[1-9]|[12][0-9]|3[01])|(0?[1-9]|[12][0-9]|3[01])(0?[1-9]|1[0-2])((?:19|20)\d{2}))\b regex matches
\b - a word boundary
(?: - start of a non-capturing group:
((?:19|20)\d{2}) - year from 20th and 21st centuries
(0?[1-9]|1[0-2]) - month
(0?[1-9]|[12][0-9]|3[01]) - day
| - or
(0?[1-9]|[12][0-9]|3[01]) - day
(0?[1-9]|1[0-2]) - month
((?:19|20)\d{2}) - year
) - end of the group
\b - word boundary.
See the regex demo.
See a Dart demo:
void main() {
final text = '13022020 and 20200213 20111919';
print(text.replaceAllMapped(RegExp(r'\b(?:((?:19|20)\d{2})(0?[1-9]|1[0-2])(0?[1-9]|[12][0-9]|3[01])|(0?[1-9]|[12][0-9]|3[01])(0?[1-9]|1[0-2])((?:19|20)\d{2}))\b'), (Match m) =>
m[4] == null ? "${m[1]}.${m[2]}.${m[3]}" : "${m[4]}.${m[5]}.${m[6]}"));
}
Returning 13.02.2020 and 2020.02.13 20.11.1919.
If Group 4 is null, the first alternative matched, so we need to use Group 1, 2 and 3. Else, we join Group 4, 5 and 6 with a dot.

How to replace 2 string letters from a String in Dart?

var string = '12345';
I want to replace 2 and 4 with 0, so I tried:
var output = string.replaceAll('2, 4', '0') // doesn't work
I am not sure if I need to use RegExp for this small stuff? Is there any other way to solve this?
You can achieve this with RegExp:
final output = string.replaceAll(RegExp(r"[24]"),'0');
[24] matches any character that is either 2 or 4.
This works
void main() {
var string = '12345';
string = string.replaceAll('2', "0");
string = string.replaceAll('4', "0");
print(string);
}

Regex for set of 6 digits from 1-49

I've a problem with define regular expression correctly. I want check sets of digits f.e.: 1,2,14,15,16,17 or 12,13,14,15,16,17 or 1,2,3,6,7,8. Every set contains 6 digits from 1 to 49. I check it by input's pattern field.
I wrote some regex but it works only for 2-digit sets.
([1-9]|[1-4][0-9],){5}([1-9]|[1-4][0-9])
Thanks for all answers :)
You forgot to group the number patterns inside the quantified group before comma and the anchors to make the regex engine match the full input string:
^(?:(?:[1-9]|[1-4][0-9]),){5}(?:[1-9]|[1-4][0-9])$
^ ^^^ ^ ^
See the regex demo.
Details
^ - start of string
(?:(?:[1-9]|[1-4][0-9]),){5} - five occurrences of:
(?:[1-9]|[1-4][0-9]) - either a digit from 1 to 9 or a number from 10 to 49`
, - a comma
(?:[1-9]|[1-4][0-9])
$ - end of string.
JS demo:
var strs = ['1,2,14,15,16,17','12,13,14,15,16,17', '1,2,3,6,7,8', '1,2,3,6,7,8,'];
var rng = '(?:[1-9]|[1-4][0-9])';
var rx = new RegExp("^(?:" + rng + ",){5}" + rng + "$");
for (var s of strs) {
console.log(s, '=>', rx.test(s));
}

Scala: concatenating a string in a regex pattern string causing issue

If I am doing this it is working fine:
val string = "somestring;userid=someidT;otherstuffs"
var pattern = """[;?&]userid=([^;&]+)?(;|&|$)""".r
val result = pattern.findFirstMatchIn(string).get;
But I am getting an error when I am doing this
val string = "somestring;userid=someidT;otherstuffs"
val id_name = "userid"
var pattern = """[;?&]""" + id_name + """=([^;&]+)?(;|&|$)""".r
val result = pattern.findFirstMatchIn(string).get;
This is the error:
error: value findFirstMatchIn is not a member of String
You may use an interpolated string literal and use a bit simpler regex:
val string = "somestring;userid=someidT;otherstuffs"
val id_name = "userid"
var pattern = s"[;?&]${id_name}=([^;&]*)".r
val result = pattern.findFirstMatchIn(string).get.group(1)
println(result)
// => someidT
See the Scala demo.
The [;?&]$id_name=([^;&]*) pattern finds ;, ? or & and then userId (since ${id_name} is interpolated) and then = is matched and then any 0+ chars other than ; and & are captured into Group 1 that is returned.
NOTE: if you want to use a $ as an end of string anchor in the interpolated string literal use $$.
Also, remember to Regex.quote("pattern") if the variable may contain special regex operators like (, ), [, etc. See Scala: regex, escape string.
Add parenthesis around the string so that regex is made after the string has been constructed instead of the other way around:
var pattern = ("[;?&]" + id_name + "=([^;&]+)?(;|&|$)").r
// pattern: scala.util.matching.Regex = [;?&]userid=([^;&]+)?(;|&|$)
val result = pattern.findFirstMatchIn(string).get;
// result: scala.util.matching.Regex.Match = ;userid=someidT;

Using regex in Scala to group and pattern match

I need to process phone numbers using regex and group them by (country code) (area code) (number). The input format:
country code: between 1-3 digits
, area code: between 1-3 digits
, number: between 4-10 digits
Examples:
1 877 2638277
91-011-23413627
And then I need to print out the groups like this:
CC=91,AC=011,Number=23413627
This is what I have so far:
String s = readLine
val pattern = """([0-9]{1,3})[ -]([0-9]{1,3})[ -]([0-9]{4,10})""".r
val ret = pattern.findAllIn(s)
println("CC=" + ret.group(1) + "AC=" + ret.group(2) + "Number=" + ret.group(3));
The compiler said "empty iterator." I also tried:
val (cc,ac,n) = s
and that didn't work either. How to fix this?
The problem is with your pattern. I would recommend using some tool like RegexPal to test them. Put the pattern in the first text box and your provided examples in the second one. It will highlight the matched parts.
You added spaces between your groups and [ -] separators, and it was expecting spaces there. The correct pattern is:
val pattern = """([0-9]{1,3})[ -]([0-9]{1,3})[ -]([0-9]{4,10})""".r
Also if you want to explicitly get groups then you want to get a Match returned. For an example the findFirstMatchIn function returns the first optional Match or the findAllMatchIn returns a list of matches:
val allMatches = pattern.findAllMatchIn(s)
allMatches.foreach { m =>
println("CC=" + m.group(1) + "AC=" + m.group(2) + "Number=" + m.group(3))
}
val matched = pattern.findFirstMatchIn(s)
matched match {
case Some(m) =>
println("CC=" + m.group(1) + "AC=" + m.group(2) + "Number=" + m.group(3))
case None =>
println("There wasn't a match!")
}
I see you also tried extracting the string into variables. You have to use the Regex extractor in the following way:
val Pattern = """([0-9]{1,3})[ -]([0-9]{1,3})[ -]([0-9]{4,10})""".r
val Pattern(cc, ac, n) = s
println(s"CC=${cc}AC=${ac}Number=$n")
And if you want to handle errors:
s match {
case Pattern(cc, ac, n) =>
println(s"CC=${cc}AC=${ac}Number=$n")
case _ =>
println("No match!")
}
Also you can also take a look at string interpolation to make your strings easier to understand: s"..."