how to replace special characters in a string by "_" - flutter

hello i have a string ch and i want to replace the special characters if it exist by "_"
how can detect all special characters is there another way .
can we use replaceAll and include all the special characters
for(int i=0; i<s.length; i++) {
var char = s[i];
if (char = "/" || char ="." || char ="$")
{
s[i] ="_"
}
}

You can do it like this with regex
_string.replaceAll(RegExp('[^A-Za-z0-9]'), '_');
This will replace all characters except alphabets and numbers with _

The best way to do this would be to use RegEx inside a .replaceAll() method.
In your case you can use a regex that matches all character other than English Alphabets..
String result = s.replaceAll(RegExp('[^A-Za-z]'), '_');
Or you can be more specific and create a regex of your requirement

Related

Single user defined function that preprocesses a python list of strings

I have the following list of strings
my_list = ["This: is the first string", "This: is another String", This: is the third string of words in the list!"]
I want to create a function that takes each string from my_list in string format and removes the "This: " (the first 6 characters), punctuations, and stop words.
This is what I have tried:
def preprocess(any_list):
[e[6:] for e in any_list]
return any_list
no_punct = [char for char in any_list if char not in string.punctuation]
no_punct = ''.join(no_punct)
clean_words = [word for word in no_punct.split() if word.lower() not in stopwords('english')]
return clean_words
preprocess(my_list)

Remove ' from a string in Swift [duplicate]

How to remove Unicode U+2018 LEFT SINGLE QUOTATION MARK from strings like -
Ghulam ‘Ali, ‘Ali Khel,‘Ali Sher ‘Alaqahdari.
I want to remove occurrences of ‘A || ‘a || ‘U || ‘u in a string to A a U u respectively.
I tried
var myString = "Sozmah Qal‘ah"
var diacriticRemovedString = myString.folding(options: .diacriticInsensitive, locale: Locale.current)
print(diacriticRemovedString)
but it doesn't work.
Since the U+2018 character doesn't appear to be treated as a diacritic, you can simple search for such characters and remove them.
Here is the Swift 4 version (as specified in your original question) that removes diacritics and these specific quotation marks:
var myString = "Sozmah Qal‘ah"
var diacriticRemovedString = myString.folding(options: .diacriticInsensitive, locale: Locale.current).replacingOccurrences(of: "‘", with: "")
print(diacriticRemovedString)
Output:
Sozmah Qalah

How do I extract only numbers from a string in Dart?

I was trying to sort the string using -
for (var t in creditcards) {
print(t['firstyear'].toString().replaceAll('/[^0-9]/', ''));
}
Its output -
Rs.500
Rs.1000
Rs.500
Rs.0
Rs.499
Rs.499 + applicable taxes
Rs.500
Rs.500
Rs.495 + taxes
Rs.0
I want to remove ' + applicable taxes' from this and parse it as integer.
Without an example of how your String is it's hard to say what or how can we avoid certain patterns. This works as long as your Strings is always in the format Letters.numbers (any amount of letters, then a dot, then any amount of numbers)
String x = 'Rs.499 + applicable taxes';
String y = ' asdhui Euro.3243 + applicable taxes';
final RegExp firstRegExp = RegExp('[a-zA-Z]+(\.[0-9]+)');
final RegExp example = RegExp(r'\w+(\.\d+)'); //this is basically the same that the one above, but also check for numbers before the dot
//consider static final RegExp to avoid creating a new instance every time a value is checked
print(firstRegExp.stringMatch(x));
print(example.stringMatch(x));
print(example.stringMatch(y));
for (var t in creditcards) {
print(example.stringMatch(t['firstyear'].toString()));
}
RegExp check for the pattern [a-zA-Z] which means any letter, + match the previous one or more times (the prvious means it will match a one or more letters, but not space, tabs or any special character), (.[0-9]+) the . checks for a dot (\ is used because . is a special character in regExp and you want to search explicitly for the dot), [0-9]+ checks for one or more numbers after the dot
RegExp is used to check for patterns, check more about it in
regExp Dart and some examples about special characters in RegExp

Extracting range of unpadded string

I'd like to extract the Range<String.Index> of a sentence within its whitespace padding. For example,
let padded = " El águila (🦅). "
let sentenceRangeInPadded = ???
assert(padded[sentenceRangeInPadded] == "El águila (🦅).") // The test!
Here's some regex that I started with, but looks like variable length lookbehinds aren't supported.
let sentenceRangeInPadded = padded.range(of: #"(?<=^\s*).*?(?=\s*$)"#, options: .regularExpression)!
I'm not looking to extract the sentence (could just use trimmingCharacters(in:) for that), just the Range.
Thanks for reading!
You may use
#"(?s)\S(?:.*\S)?"#
See the regex demo.
Details
(?s) - a DOTALL modifier making . match any char, including line break chars
\S - the first non-whitespace char
(?:.*\S)? - an optional non-capturing group matching
.* - any 0+ chars as many as possible
\S - up to the last non-whitespace char.

How can I detect if a string contains punctuation marks at the end?

Lets assume I have the string:
"Hello I like your shoes #today...!"
I am tokenizing the string by spaces:
return [string componentsSeparatedByString:#" "];
So my array contains:
Hello
I
like
your
shoes
#today...!
I want to focus on "#today...!" any word that has a # in the prefix I am changing the font color.
How can I make sure that only "#today" has its font color changed?
I would basically like to figure out if a word has a punctuation mark at the end, and change the color for characters before the punctuation mark.
I'm confused by your question. Are you trying to detect string with punctuation marks at the end or with # marks at the beginning?
In any case:
for (NSString *word in [string componentsSeparatedByString:#" "]) {
if ([word hasPrefix:#"#"])NSLog(#"%# starts with #",word);
if ([word hasSuffix:#"!"])NSLog(#"%# end with !",word);
}
You could do something like:
if ([[NSCharacterSet symbolCharacterSet] characterIsMember:[word characterAtIndex:0]]) NSLog(#"%#", word);
This is to test for a symbol at the beginning of the string--to test at the end, you would use [word characterAtIndex:([word length] - 1)]
EDIT: OK, I think I understand the question now. If you want want to only change the color of characters before the color set, you could do something along the lines of:
NSRange punctCharRange = [word rangeOfCharacterFromSet:[NSCharacterSet punctuationCharacterSet]];
for (int i = 0; i < punctCharRange.location; i++) {
//change the color of the character
}
Consider using RegexKitLite and this method:
- (NSRange)rangeOfRegex:(NSString *)regex
options:(RKLRegexOptions)options
inRange:(NSRange)range
capture:(NSInteger)capture
error:(NSError **)error;
The regex you'd want is something like #"#\\S+\\b". This regex says "Find a '#' character followed by 1 or more non-space characters followed by a word boundary".
This would then return the range of the matched regex inside the string to match.
The following code should look from the end of word toward the beginning until it finds a character that is not alphanumeric, test if it found such a character and if so, remove anything after that character. (untested code)
NSString *wordWithoutTrailingNonAlphanum;
NSRange firstNonAlphanumCharFromEnd =
[word rangeOfCharacterFromSet:[NSCharacterSet alphanumericCharacterSet]
options:NSBackwardsSearch];
if (firstNonAlphanumCharFromEnd.location != NSNotFound) {
wordWithoutTrailingNonAlphanum =
[word substringToIndex:(firstNonAlphanumCharFromEnd.location + 1)];
}
I tried tokenizing all words that begin with # and splitting it based on the NSPunctuationCharacterSet. This works, however I lose the punctuation marks.