Equivalent of Java's Matcher.lookingAt() in Objective C - java

I am porting a framework from Java to Objective C which heavily depends on regular expressions. Unfortunately the Java regular expressions API is a lot different from the Objective C API.
I am trying to use the NSRegularExpression class to evaluate the regular expressions. In Java this is completely different: you have to use the Pattern and Matcher classes.
There is something I can't figure out (among other things). What is the equivalent of Matcher.lookingAt() in Objective C? To put it in code. What would be the Objective C translation of the following code?
Pattern pattern = Pattern.compile("[aZ]");
boolean lookingAt = pattern.matcher("abc").lookingAt();
Thanks to anyone who knows! (btw the above example assigns true to the lookingAt boolean)

I figured it out! This is the NSRegularExpression equivalent of the Java code:
NSError *error = nil;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"[aZ]" options:0 error:&error];
if (error) {
// Do something when an error occurs
}
NSString *candidate = #"abc";
BOOL lookingAt = [expression numberOfMatchesInString:candidate options:NSMatchingAnchored range:NSMakeRange(0, candidate.length)] > 0;
The emphasis here lies on the NSMatchingAnchored option when executing the expression! The docs say:
NSMatchingAnchored Specifies that matches are limited to those at the
start of the search range. See
enumerateMatchesInString:options:range:usingBlock: for a description
of the constant in context.
That's exactly what I was looking for!

You may do something like
NSString *regex = #"ObjC";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF CONTAINS %#", regex];
if( [predicate evaluateWithObject:myString])
NSLog(#"matches");
else
NSLog(#"does not match");
take a look at Predicate Format String Syntax guide for further options.

Related

How to reference attribute from .bnf parser in JFlex?

I'm using a .bnf parser to detect specific expressions and I'm using JFlex to detect the different sections of these expressions. My issue is, some of these expressions may contain nested expressions and I dont know how to handle that.
I've tried to include the .bnf parser in my JFlex by using %include, then referencing the expression in the relative macro using PARAMETERS = ("'"[:jletter:] [:jletterdigit:]*"'") | expression. This fails as JFlex reports the .bnf to be malformed.
Snippet of JFlex:
%{
public Lexer() {
this((java.io.Reader)null);
}
%}
%public
%class Lexer
%implements FlexLexer
%function advance
%type IElementType
%include filename.bnf
%unicode
PARAMETERS= ("'"[:jletter:] [:jletterdigit:]*"'") | <a new expression element>
%%
<YYINITIAL> {PARAMETERS} {return BAD_CHARACTER;} some random return
Snippet of .bnf parser:
{
//list of classes used.
}
expression ::= (<expression definition>)
Any input would be greatly appreciated. Thanks.
I've found the solution to my issue. In further depth, the problem was in both my grammar file and my flex file. To solve the issue, I recursively called the expression in the grammar file like so:
expression = (start value expression? end)
With the JFlex, I declared numerous states until I found a way to chain together and endless amount of expressions. Looks a little like this:
%state = WAITING_EXPRESSION
<WAITING_NEXT> "<something which indicates start of nested expression>" { yybegin(WAITING_EXPRESSION); return EXPRESSION_START; }

Any Java support for scripting language syntax similar to Foobar2000:Title Formatting Reference

Previously Id asked this question Putting a simple expression language into java about allowing the user to enter a formatting mask with support for if statements, substrings and the like.
The answer to use Script Engine with javascript worked , however the javascript syntax is not very easy for users
(albumartist.length>0 ? albumartist +'-' :(artist.length>0 ? artist + '-' : ' ')) + (album.length>0 ? album + '-' :'') + (trackno.length>0 ? trackno + '-' :'') + title
could give output
U2-Boy-Twilight-02
but an easier syntax would be something like
if(%albumartist%,%artist%)-if(%album%,%album%-)if(%trackno%,%trackno-)%title
The main difference being is we don't have to explicity concatenate strings with '+' or quote string literals with ' '
which is similar to the Foobar title formatting reference detailed at http://wiki.hydrogenaudio.org/index.php?title=Foobar2000:Title_Formatting_Reference#.24if2.28a.2Celse.29 but there is not a physical implemention of this I could parse in Java.
Any ideas ?
AFAIK, only javascript (ECMAScript) is supported in the standard JDK. You can check what engines are available with the code below.
Other engines are available in the scripting project, but I don't believe that the language you mention is part of them.
If you feel like it (and have a lot of spare time), you can create your own scripting engine.
You can read more about engines here, there and there.
Finally you could "simply" parse the FooBar2000 syntax in Java.
To summarise, what you are trying to do does not sound like an easy task - good luck! ;-)
public static void main(String[] args) {
ScriptEngineManager mgr = new ScriptEngineManager();
List<ScriptEngineFactory> factories =
mgr.getEngineFactories();
for (ScriptEngineFactory factory : factories) {
String engName = factory.getEngineName();
String engVersion = factory.getEngineVersion();
String langName = factory.getLanguageName();
String langVersion = factory.getLanguageVersion();
System.out.printf("Script Engine: %s (%s)\n", engName, engVersion);
System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion);
}
}

replace method not working with global modifier

I am trying to replace a character in a string with multiple occurences in Javascript.
String a1 = "There is a man over there";
when i use replace("e","x");
it will replace only the first occurrence of e.
So i am trying to use the g modifier like this replace(/e/g,"x");
But i am facing with this error Syntax error on tokens, Expression expected instead
I am not sure what i am doing wrong here.
replace(/e/g,"x") would be valid in JavaScript but not in Java. For Java just use the following:
String a1 = "There is a man over there";
String replaced = a1.replaceAll("e", "x"); // "Thxrx is a man ovxr thxrx"
The problem is you are mixing Java and Javascript which have absolutely nothing to do with each other.
Since you said you are trying in Javascript, do this:
var a1 = "There is a man over there"; // not String a1...
a1.replace(/e/g, 'x');

Capturing dot and comma in Java RegExp

I have following code in Java:
Pattern fieldsPattern = Pattern.compile("(\"([^\"]+)\")|"
+"("+this.field_tag+"([0-9a-zA-Z_]+))");
Matcher fieldsMatcher = fieldsPattern.matcher(field);
while(fieldsMatcher.find())
{
//...
}
This code should capture expressions like "expression" and :expression (field_tag is just ":"). The problem occurs when I try to capture an expression like: "10.1" or "10,1". It dosen't work.
But expressions:
"10-1",
"10+1"
works as expected.
I also tried use this regexp on regexpal.com - site with javascript implementation of RegExp. On this site expressions like "10.1" and "10,1" works fine.
Is there any difference in java vs javascript in capturing dots? What am I doing wrong?
This works for me
Pattern fieldsPattern = Pattern.compile("(\"[^\"]+\")");
String field =" aa \"10\" \"10.1\" and \"10,1\"";
Matcher fieldsMatcher = fieldsPattern.matcher(field);
while(fieldsMatcher.find()) {
System.out.println(fieldsMatcher.group());
}
prints
"10"
"10.1"
"10,1"
The second set of brackets in the regex appear to be redundant, but are harmless.

GWT : how to get regex(Pattern and Matcher) working in client side

We're using GWT 2.03 along with SmartGWT 2.2. I'm trying to match a regex like below in client side code.
Pattern pattern = Pattern.compile("\\\"(/\d+){4}\\\"");
String testString1 = "[ \"/2/4/5/6/8\", \"/2/4/5/6\"]";
String testString2 = "[ ]";
Matcher matcher = pattern.matcher(testString1);
boolean result = false;
while (matcher.find()) {
System.out.println(matcher.group());
}
It appears that Pattern and Matcher classes are NOT compiled to Javascript by the GWTC compiler and hence this application did NOT load. What is the equivalent GWT client code so that I can find regex matches within a String ?
How have you been able to match regexes within a String in client-side GWT ?
Thank you,
Just use the String class to do it!
Like this:
String text = "google.com";
if (text.matches("(\\w+\\.){1,2}[a-zA-Z]{2,4}"))
System.out.println("match");
else
System.out.println("no match");
It works fine like this, without having to import or upgrade or whatever.
Just change the text and regex to your liking.
Greetings, Glenn
Consider upgrading to GWT 2.1 and using RegExp.
Use GWT JSNI to call native Javascript regexp:
public native String jsRegExp(String str, String regex)
/*-{
return str.replace(/regex/); // an example replace using regexp
}
}-*/;
Perhaps you could download the RegExp files from GWT 2.1 and add them to your project?
http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/regexp/
Download GWT 2.1 incl source, add that directory somewhere in your project, then add the reference to the "RegExp.gwt.xml" using the <inherits> tag from your GWT XML.
I'm not sure if that would work, but it'd be worth a shot. Maybe it references something else GWT 2.1 specific which you don't have, but I've just checked out the code a bit and I don't think it does.
GWT 2.1 now has a RegExp class that might solve your problem:
// Compile and use regular expression
RegExp regExp = RegExp.compile(patternStr);
MatchResult matcher = regExp.exec(inputStr);
boolean matchFound = regExp.test(inputStr);
if (matchFound) {
Window.alert("Match found");
// Get all groups for this match
for (int i=0; i<=matcher.getGroupCount(); i++) {
String groupStr = matcher.getGroup(i);
System.out.println(groupStr);
}
}else{
Window.alert("Match not found");
}

Categories