I have below as string
name : abc,
position : 2
I want to make replace so that the string becomes as below
name : "abc",
position : 2
What change I want to do is abc will have double quotes so abc becomes "abc".
Note: abc is dynamic, it can be anything as below.
name : Test,
position : 2
name : Great,
position : 2
name : developers,
position : 2
Any idea how this can be done?
I suggest using \\b(name\\s*:\\s*)(.+), pattern and replace with $1"$2",:
NSError *error = nil;
NSString *myText = #"name : abc,\nposition : 2";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\b(name\\s*:\\s*)(.+)," options:nil error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:#"$1\"$2\","];
NSLog(#"%#", modifiedString);
See the Objective-C demo
Details:
\\b - a leading word boundary
(name\\s*:\\s*) - Group 1 matching name, 0+ whitespaces, : and 0+ whitespaces again
(.+) - any 0+ chars other than line break chars as many as possible
, - comma
The replacement pattern - $1"$2", - inserts Group 1 contents, ", Group 2 contents and ",.
See the regex demo.
Related
My string looks like this:
dog-3
dog-2
dog-1
dog0
aaaaaaa
dog1
dog2
dog3
dog4
bbbbbbb
dog5
dog6
dog7
dog8
ccccccc
dog9
dog10
dog11
aaaaaaa
dog12
dog13
dog14
dog15
bbbbbbb
dog16
dog17
dog18
dog19
ccccccc
dog20
dog21
dog22
dog23
I am trying to write a regular expression to match a pattern "^aaaaaaa$.+^bbbbbbb$.+^ccccccc"
This is my code where str is described above
NSRegularExpression *conflictMarker = [NSRegularExpression regularExpressionWithPattern:#"^aaaaaaa$.+^bbbbbbb$.+^ccccccc"
options:NSRegularExpressionDotMatchesLineSeparators|NSRegularExpressionAnchorsMatchLines
error:&error];
[conflictMarker enumerateMatchesInString:str options:0
range:NSMakeRange(0, str.length)
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange matchRange = [result range];
NSString *subst = [str substringWithRange:matchRange];
NSInteger a = result.numberOfRanges;
NSLog(#"%ld ", a);
for (NSInteger a = 0; a < result.numberOfRanges; a++) {
NSRange matchRange = [result rangeAtIndex:a];
NSString *subst = [str substringWithRange:matchRange];
NSLog(#"\n%#", subst);
}
}];
My expectation from the above code was to receive two matches; the first match contains a range from "dog1" to "dog8" and second range from "dog12" to "dog19" but I only get 1 match with a range from "dog1" to "dog19".
What am I doing wrong here and how can I correct it?
Thanks in advance.
You may use
^aaaaaaa(?:\R(?!(?:bbbbbbb|aaaaaaa|ccccccc)$).*)*\Rbbbbbbb(?:\R(?!(?:aaaaaaa|ccccccc)$).*)*\Rccccccc
See the regex demo. Make sure you change the regex options to options:NSRegularExpressionAnchorsMatchLines for this pattern to work:
NSRegularExpression *conflictMarker = [NSRegularExpression regularExpressionWithPattern:#"^aaaaaaa(?:\\R(?!(?:bbbbbbb|aaaaaaa|ccccccc)$).*)*\\Rbbbbbbb(?:\\R(?!(?:aaaaaaa|ccccccc)$).*)*\\Rccccccc"
options:NSRegularExpressionAnchorsMatchLines
error:&error];
Details
^ - start of a line
aaaaaaa - a string
(?:\R(?!(?:bbbbbbb|aaaaaaa|ccccccc)$).*)* - 0 or more occurrences of
\R(?!(?:bbbbbbb|aaaaaaa|ccccccc)$) - a line break sequence that is not followed with bbbbbbb, aaaaaaa, or ccccccc and the end of a line
.* - any 0+ chars other than line break chars, as many as possible
\R - a line break sequence
bbbbbbb - a string
(?:\R(?!(?:aaaaaaa|ccccccc)$).*)* - 0 or more occurrences of
\R(?!(?:aaaaaaa|ccccccc)$) - a line break sequence that is not followed with aaaaaaa or ccccccc and the end of a line
.* - any 0+ chars other than line break chars, as many as possible
\R - a line break sequence
ccccccc - a string.
I need to validate phone number. Below is the code snippet
-(BOOL) validatePhone:(NSString*) phoneString
{
NSString *regExPattern = #"^[6-9]\\d{9}$"; ORIGINAL
// NSString *regExPattern = #"^[6-9](\\d)(?!\1+$)\\d*$";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:phoneString options:0 range:NSMakeRange(0, [phoneString length])];
NSLog(#"%lu", (unsigned long)regExMatches);
if (regExMatches == 0) {
return NO;
}
else
return YES;
}
I want to reject phone number that is in sequnce example
9999999999, 6666677777
It seems you want to disallow 5 and more identical consecutive digits.
Use
#"^[6-9](?!\\d*(\\d)\\1{4})\\d{9}$"
See the regex demo
Details
^ - start of string
[6-9] - a digit from 6 to 9
(?!\d*(\d)\1{4}) - a negative lookahead that fails the match if, immediately to the right of the current location, there is
\d* - 0+ digits
(\d) - a digit captured into Group 1
\1{4} - the same digit as captured in Group 1 repeated four times
\d{9} - any 9 digits
$ - end of string (replace with \z to match the very end of string do disallow the match before the final LF symbol in the string).
Note that \d is Unicode aware in the ICU regex library, thus it might be safer to use [0-9] instead of \d.
I want a regular expression for first name that can contain
1)Alphabets
2)Spaces
3)Apostrophes
Exp: Raja, Raja reddy, Raja's,
I used this ^([a-z]+[,.]?[ ]?|[a-z]+[']?)+$ but it is failing to recognise Apostrophes (').
- (BOOL)validateFirstNameOrLastNameOrCity:(NSString *) inputCanditate {
NSString *firstNameRegex = #"^([a-z]+[,.]?[ ]?|[a-z]+[']?)+$";
NSPredicate *firstNamePredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES[c] %#",firstNameRegex];
return [firstNamePredicate evaluateWithObject:inputCanditate];
}
May I recommand ^[A-Z][a-zA-Z ']* ?
// The NSRegularExpression class is currently only available in the Foundation framework of iOS 4
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[A-Z][a-zA-Z ']*" options:NSRegularExpressionAnchorsMatchLines error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:searchText options:0 range:NSMakeRange(0, [string length])];
return numberOfMatches > 1;
^[A-Z] : Force start with a capital letter from A to Z
[a-zA-Z ']* : followed by any number of charactere that an be 'a' to 'z', 'A' to 'Z', space or simple quote
I think you are looking for a pattern like this: ^[a-zA-Z ']+$
However, this is pretty bad. What about umlauts, accents, and a whole lot other letters that are not part of the ASCII alphabet?
A better solution would be to allow any kind of letter from any language.
To do so you can use the Unicode "letter" category \p{L}, e.g. ^[\p{L}]+$.
.. or you could just drop that rule all together - as reasonably suggested.
I have an application that communicates with a serial port. I am looking to create a packet descriptor with regex that can recognize the expression.
The string is !$S0, 0, 48, 3and I want the regex to recognize any digit.
- (IBAction)getStatus:(id)sender
{
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"[(!$S\\d,\\s\\d,\\s\\d,\\s\\d)]" options:0 error:0];
self.getStatus = [[ORSSerialPacketDescriptor alloc] initWithRegularExpression:regex maximumPacketLength:20 userInfo:nil];
[self.serialPort startListeningForPacketsMatchingDescriptor:self.getStatus];
NSString *command = #"$S";
command = [command stringByAppendingString:[self lineEndingString]];
NSData *dataToSend = [command dataUsingEncoding:NSUTF8StringEncoding];
[self.serialPort sendData:dataToSend];
}
I expect it to pull the whole response so that I can process the string here:
- (void)serialPort:(ORSSerialPort *)serialPort didReceivePacket:(NSData *)packetData matchingDescriptor:(ORSSerialPacketDescriptor *)descriptor {
NSString *asciString = [[NSString alloc] initWithData:packetData encoding:NSASCIIStringEncoding];
NSLog(#"package[asci]: %#", asciString);
if (descriptor == self.getStatus) {
}
}
Any help would be appreciated.
You may use
#"!\\$S\\d+(?:,\\s+\\d+){3}"
Enclose with ^ (start of string) and $ (end of string) if you plan to match the string exactly:
#"^!\\$S\\d+(?:,\\s+\\d+){3}$"
See the regex demo
Details
^ - start of string
! - a !
\\$ - a $ symbol (must be escaped)
S - an S letter
\\d+ - 1 or more digits
(?:,\\s+\\d+){3} - 3 consecutive sequences of:
, - a comma
\\s+ - 1 or more whitespaces
\\d+ - 1 or more digits
$ - end of string.
I'm pretty new to Regex and I'm just trying to get my head around it. The string I am trying to search through is this:
100 ON 12C 12,41C High Cool OK 0
101 OFF 32C 04,93C Low Dry OK 1
102 ON 07C 08,27C High Dry OK 0
What I am trying to do is work out the part to find the part 32C from the string. If possible, would the code be able to be changed a little each time in order to find the Nth occurrence of the word in the String. If it makes any difference I am going to be using this code in an iPhone application and thus Objective-C.
Your example is line-oriented and of equal weight (at the same time) biased towards the beginning of the line in the string.
If your engine flavor does grouping, you should be able to specify an occurance quantifier that will get you a single exact answer, without the need to do arrays and such.
In both cases the answer is in capture buffer 1.
examples:
$occurance = "2";
---------
/(?:[^\n]*?(\d+C)[^\n]*.*?){$occurance}/s
---------
or
---------
/(?:^.*?(\d+C)[\S\s]*?){$occurance}/m
expanded:
/
(?:
[^\n]*?
( \d+C )
[^\n]* .*?
){2}
/xs
/
(?:
^ .*?
( \d+C )
[\S\s]*?
){2}
/xm
You could try something like the following. You will have to replace regex_pattern with your regular expression pattern. In your case, regex_pattern should be something like #"\\s\\d\\dC" (a whitespace character (\\s) followed by a digit (\\d) followed by a digit (\\d) followed an upper-case letter C.
You may also wish to remove the NSRegularExpressionCaseInsensitive option if you can be sure that the letter C will never be lower case.
NSError *error = nil;
NSString *regex_pattern = #"\\s\\d\\dC";
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:regex_pattern
options:(NSRegularExpressionCaseInsensitive |
NSRegularExpressionDotMatchesLineSeparators)
error:&error];
NSArray *arrayOfMatches = [regex matchesInString:myString
options:0
range:NSMakeRange(0, [myString length])];
// arrayOfMatches now contains an array of NSRanges;
// now, find and extract the 2nd match as an integer:
if ([arrayOfMatches count] >= 2) // be sure that there are at least 2 elements in the array
{
NSRange rangeOfSecondMatch = [arrayOfMatches objectAtIndex:1]; // remember that the array indices start at 0, not 1
NSString *secondMatchAsString = [myString substringWithRange:
NSMakeRange(rangeOfSecondMatch.location + 1, // + 1 to skip over the initial space
rangeOfSecondMatch.length - 2)] // - 2 because we ignore both the initial space and the final "C"
NSLog(#"secondMatchAsString = %#", secondMatchAsString);
int temperature = [secondMatchAsString intValue]; // should be 32 for your sample data
NSLog(#"temperature = %d", temperature);
}