I need a little kickstart on regex on the iPhone. Actually I am dealing with UITextField.text. If the value of the text is empty and if the value already exist, I can able to deal it. But, if the value is simply white spaces, I do not want to use it. So, if the value is like " " or " folder", I want the value to be "" and "folder" respectively.
I planned to use NSRegularExpression to remove the white space and went through the documents. But it was little confusing. So, help me to come out of the problem of removing white space from the given string. Thank you in advance.
Edit: you need to trim string, so no regular expression is needed, simply use:
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
The regexp would be:
/\s+/g
You would then replace that with ""
How you do that through iOS syntax for the replacement I don't know, but that's the regExp for it all :)
A more practical question is, How to trim and condense white-spaces,
let text: String? = " I don't know you ! " // expected result: "I don't know you!"
let charSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
if let trimmedText = text?.componentsSeparatedByCharactersInSet(charSet).filter({!$0.isEmpty}).joinWithSeparator(" ") {
print(trimmedText) // I don't know you!
}
Related
I have a string variable in PowerShell which contains the value:
NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8
I am attempting to get the beginning portion of that string into it's own variable by identifying the index of the "|" character and using a substring function to extract the first portion of the string, in this case "NFP". I am not sure how to escape the "|" so I can use it properly. It doesn't seem to recognize it at all. My latest attempt is as follows:
$PolicyManual = $Item["PolicyManual"]
write-host $PolicyManual #Displays NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8
if ($PolicyManual.Contains([regex]::escape("|"))) {
$PolcyManual = $PolicyManual.Substring(0, $PolicyManual.IndexOf([regex]::escape("|")))
}
I'm sure this is simple, but I can't figure out how to make it work. Can anyone offer assistance to a PowerShell novice?
Thanks.
The problem is that .contains method doesn't know about regex and you are never entering the if condition because of this. When you do [regex]::escape("|"), the method is looking for a literal \|.
Try this instead:
$PolicyManual = "NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8"
if ($PolicyManual.Contains('|')) {
$element0, $element1 = $PolicyManual.Split('|')
$element0 #=> NFP
$element1 #=> 8dc3b47a-48eb-4696-abe2-48729beb63c8
}
I'm hoping this is an easy question, and that I'm just not seeing the forest due to all the trees.
I have a string in flutter than came from a REST API that looks like this:
"What\u0027s this?"
The \u is causing a problem.
I can't do a string.replaceAll("\", "\") on it as the single slash means it's looking for a character after it, which is not what I need.
I tried doing a string.replaceAll(String.fromCharCode(0x92), "") to remove it - That didn't work.
I then tried using a regex to remove it like string.replaceAll("/(?:\)/", "") and the same single slash remains.
So, the question is how to remove that single slash, so I can add in a double slash, or replace it with a double slash?
Cheers
Jase
I found the issue. I was looking for hex 92 (0x92) and it should have been decimal 92.
I ended up solving the issue like this...
String removeUnicodeApostrophes(String strInput) {
// First remove the single slash.
String strModified = strInput.replaceAll(String.fromCharCode(92), "");
// Now, we can replace the rest of the unicode with a proper apostrophe.
return strModified.replaceAll("u0027", "\'");
}
When the string is read, I assume what's happening is that it's being interpreted as literal rather than as what it should be (code points) i.e. each character of \0027 is a separate character. You may actually be able to fix this depending on how you access the API - see the dart convert library. If you use utf8.decode on the raw data you may be able to avoid this entire problem.
However, if that's not an option there's an easy enough solution for you.
What's happening when you're writing out your regex or replace is that you're not escaping the backslash, so it's essentially becoming nothing. If you use a double slash, that solve the problem as it escapes the escape character. "\\" => "\".
The other option is to use a raw string like r"\" which ignores the escape character.
Paste this into https://dartpad.dartlang.org:
String withapostraphe = "What\u0027s this?";
String withapostraphe1 = withapostraphe.replaceAll('\u0027', '');
String withapostraphe2 = withapostraphe.replaceAll(String.fromCharCode(0x27), '');
print("Original encoded properly: $withapostraphe");
print("Replaced with nothing: $withapostraphe1");
print("Using char code for ': $withapostraphe2");
String unicodeNotDecoded = "What\\u0027s this?";
String unicodeWithApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '\'');
String unicodeNoApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '');
String unicodeRaw = unicodeNotDecoded.replaceAll(r"\u0027", "'");
print("Data as read with escaped unicode: $unicodeNotDecoded");
print("Data replaced with apostraphe: $unicodeWithApostraphe");
print("Data replaced with nothing: $unicodeNoApostraphe");
print("Data replaced using raw string: $unicodeRaw");
To see the result:
Original encoded properly: What's this?
Replaced with nothing: Whats this?
Using char code for ': Whats this?
Data as read with escaped unicode: What\u0027s this?
Data replaced with apostraphe: What's this?
Data replaced with nothing: Whats this?
Data replaced using raw string: What's this?
I am struggling with this regular expression.
$glossary_search[] = "/(^|>|\\s)".$glossary["glossary_name"]."($|<|\\s)/i";
$glossary_replace[] = "\$1<a href='/jargon-buster/".tapestry_hyphenate($glossary["glossary_name"]).".html' title='".$glossary["glossary_name"]."' target='_blank'>".$glossary["glossary_name"]."</a>\$2";
return preg_replace($glossary_search,$glossary_replace,$text);
I am trying to replace words in a product description with a hyperlink. The code above works if the word has a space either side but does not work if it has a full stop, comma or "<". Can anyone spot my mistake?
Thanks,
Simon
I think you might need to use preg_quote and htmlentities?
$glossary_search[] = "/(^|>|\\s)".preg_quote(htmlentities($glossary["glossary_name"],ENT_COMPAT,'UTF8'))."($|<|\\s)/i";
$glossary_replace[] = "\$1<a href='/jargon-buster/".tapestry_hyphenate($glossary["glossary_name"]).".html' title='".$glossary["glossary_name"]."' target='_blank'>".$glossary["glossary_name"]."</a>\$2";
return preg_replace($glossary_search,$glossary_replace,$text);
Hi Friends, I have a small question,
I have a paragraph of string, now I want to delete some words from that para
aaaaaaaaaaaaaaaaa*bbbbbbbbb*aaaaaaaaaaaaaa.
Now, suppose I want to delete the "bbbbbbbb" fromthe above para and I am using the following method
mySpeechText = [[mySpeechText stringByReplacingOccurrencesOfString:strTemp withString:#""] retain];
but this method is replacing the "bbbbbbbb" with blank spaces, ie, " " and I am getting
aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa;
and I want aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; without any space. so how can I delete the "bbbbbbbb" rather replacing it. Thanks-
If I am not clear plz let me know.
Try this
mySpeechText=[mySpeechText stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"bbbbbbbb"]];
Trying to display a hebrew string that starts with a number, always displays the number at the end of the string like so: 1. יום שישי בבוקר
but I need the number to be displayed at the right side of the text-
any solution to that?
It happens with UILabel & UITextField & UITextView
and trying to write the number at the left side also produce the same resault.
Playing with combinations of UITextAlignment will doesn't help.
You don't need to change any setting on UILabel, just put the character with unicode 0x200F before your string. This is the reason:
In Unicode many characters have a specific directionality, which lets the system know it has to be written, say LTR, like سلام. The paragraph usually uses the direction of its first character. That's why your string without the number is typed from right to left automatically.
Now some characters, like numbers, have "weak" directionality, so they basically take that of their surrounding. When you type "1. בבוקר", the system first sees 1, so takes the usual LTR direction. Changing the alignment won't help, as it just shifts the whole text to right, or center.
To solve this issue, Unicode has two marker characters (LTR: 0x200E, RTL:200F). These are invisible, but dictate the directionality. So while "1. בבוקר" is...
בבוקר
if you type "#x200F" + "1. בבוקר" it will display like this:
1. בבוקר
Building on Mo's great answer:
This is the code Obj-C:
NSString *RTFstr = "1. בבוקר"; //This could be any right-to-left string
NSString *directionalString = [#"\u200F" stringByAppendingString:[note text]];
[someUITextView setString:directionalString];
And it actually works...
I had a slightly different problem but Mo's answer gave me the clue.
I wanted to get a LTR text (like "abcd") displayed in RTL direction ("dcba") without having to do myself the string reversing. Turns out enclosing the string between \u202E and \u202C does the trick.
I also recommend reading the following page as it gives a very good explanation of all these unicode magic:
http://www.iamcal.com/understanding-bidirectional-text/
Swift anybody?
extension String {
func stringByForcingWritingDirectionLTR() -> String {
return "\u{200E}".stringByAppendingString(self)
}
func stringByForcingWritingDirectionRTL() -> String {
return "\u{200F}".stringByAppendingString(self)
}
}
not sure if there's fancier way to do this but you might want to try something like this:
NSString *test = #"12. just a teststring";
NSString *number = [test substringToIndex: [test rangeOfString: #" "].location];
NSString *text = [test substringFromIndex: [test rangeOfString: #" "].location];
test = [NSString stringWithFormat: #"%# %#", text, number];
// test == "just a teststring 12."