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

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);
}

Related

Trim String/Text in Flutter

Hi I tried to trim a link in flutter
Currently I am looking into regexp but I think that is not possible
This is the link in full:
http://sales.local/api/v1/payments/454/ticket/verify?token=jhvycygvjhbknm.eyJpc3MiOiJodH
What I am trying to do is to trim the link like this:
http://sales.local/api/v1/payments/454
Kindly advise on best practise to trim string/text in flutter. Thanks!
try to use substring() :
String link = 'http://sales.local/api/v1/payments/454/ticket/verify?token=jhvycygvjhbknm.eyJpc3MiOiJodH';
String delimiter = '/ticket';
int lastIndex = link.indexOf(delimiter);
String trimmed = link.substring(0,lastIndex);
//print(trimmed);
input string print for Flutter:
String str2 = "-hello Friend- ";
print(str2.trim());
Output Print : -hello Friend-
NOte: Here last space remove from string.
1.Right Method:
var str1 = 'Dart';
var str2 = str1.trim();
identical(str1, str2);
2.Wrong Method
'\tTest String is Fun\n'.trim(); // 'Test String is Fun'
main(List<String> args) {
String str =
'http://sales.local/api/v2/paymentsss/45444/ticket/verify?token=jhvycygvjhbknm.eyJpc3MiOiJodH';
RegExp exp = new RegExp(r"((http|https)://sales.local/api/v\d+/\w.*?/\d*)");
String matches = exp.stringMatch(str);
print(matches); // http://sales.local/api/v2/paymentsss/45444
}

how to convert in time format with regex in dart

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})

Most efficient way to remove leading zeros from Swift 3 string

I have a string such as "00123456" that I would like to have in an string "123456", with the leading zeros removed.
I've found several examples for Objective-C but not sure best way to do so with Swift 3.
Thanks
You can do that with Regular Expression
let string = "00123456"
let trimmedString = string.replacingOccurrences(of: "^0+", with: "", options: .regularExpression)
The benefit is no double conversion and no force unwrapping.
Just convert the string to an int and then back to a string again. It will remove the leading zeros.
let numberString = "00123456"
let numberAsInt = Int(numberString)
let backToString = "\(numberAsInt!)"
Result: "123456"
First, create Validator then use it in any class.
This is an example and it works :)
This is swift 4.0
class PhoneNumberExcludeZeroValidator {
func validate(_ value: String) -> String {
var subscriberNumber = value
let prefixCase = "0"
if subscriberNumber.hasPrefix(prefixCase) {
subscriberNumber.remove(at: subscriberNumber.startIndex)
}
return subscriberNumber
}
}
example for usage:
if let countryCallingCode = countryCallingCodeTextField.text, var subscriberNumber = phoneNumberTextField.text {
subscriberNumber = PhoneNumberExcludeZeroValidator().validate(subscriberNumber)
let phoneNumber = "\(countryCallingCode)\(subscriberNumber)"
registerUserWith(phoneNumber: phoneNumber)
}
let number = "\(String(describing: Int(text)!))"

extract the first word from a string - regex

I have the following string:
str1 = "cat-one,cat2,cat-3";
OR
str1 = "catone,cat-2,cat3";
OR
str1 = "catone";
OR
str1 = "cat-one";
The point here is words may/may not have "-"s in it
Using regex:
How could I extract the 1st word?
Appreciate any help on this.
Thanks,
L
It's pretty easy, just include allowed characters in brackets:
^([\w\-]+)
An approach not using a regex: assuming the first word is delimited always by a comma "," you can do this:
var str1 = "cat-one";
var i = str1.indexOf(",");
var firstTerm = i == -1 ? str1 : str1.substring(0, i);
Edit: Assumed this was a javascript question, for some reason.
If someone, one day would like to do it in Swift here you go with an extension :
extension String {
func firstWord() -> String? {
var error : NSError?
let internalExpression = NSRegularExpression(pattern: "^[a-zA-Z0-9]*", options: .CaseInsensitive, error: &error)!
let matches = internalExpression.matchesInString(self, options: nil, range:NSMakeRange(0, countElements(self)))
if (matches.count > 0) {
let range = (matches[0] as NSTextCheckingResult).range
return (self as NSString).substringWithRange(range)
}
return nil
}
}
To use it just write:
myString.firstWord()

Replace each RegExp match with different text in ActionScript 3

I'd like to know how to replace each match with a different text?
Let's say the source text is:
var strSource:String = "find it and replace what you find.";
..and we have a regex such as:
var re:RegExp = /\bfind\b/g;
Now, I need to replace each match with different text (for example):
var replacement:String = "replacement_" + increment.toString();
So the output would be something like:
output = "replacement_1 it and replace what you replacement_2";
Any help is appreciated..
You could also use a replacement function, something like this:
var increment : int = -1; // start at -1 so the first replacement will be 0
strSource.replace( /(\b_)(.*?_ID\b)/gim , function() {
return arguments[1] + "replacement_" + (increment++).toString();
} );
I came up with a solution finally..
Here it is, if anyone needs:
var re:RegExp = /(\b_)(.*?_ID\b)/gim;
var increment:int = 0;
var output:Object = re.exec(strSource);
while (output != null)
{
var replacement:String = output[1] + "replacement_" + increment.toString();
strSource = strSource.substring(0, output.index) + replacement + strSource.substring(re.lastIndex, strSource.length);
output = re.exec(strSource);
increment++;
}
Thanks anyway...
leave off the g (global) flag and repeat the search with the appropriate replace string. Loop until the search fails
Not sure about actionscript, but in many other regex implementations you can usually pass a callback function that will execute logic for each match and replace.