Sean Sean - 7 months ago 17
Java Question

RegEx test from JavaScript to Java

I'm trying to migrate the following algorithm from an angular service into the backend, thus from JavaScript to Java.

Can you help me get to the same result in Java as I do in js?

var UA = navigator.userAgent,
isIOS = /ip(hone|od|ad)/i.test(UA),
isSafari = /(mac os x).*version\/\d(.\d)+ (mobile\/\w{5,} )?safari/i.test(UA),
isSafari5 = /(mac os x).*version\/5[.\d]+ (mobile\/\w{5} )?safari/i.test(UA),
isAndroid = /android/i.test(UA),
isAndroidBrowser = isAndroid && !/chrome|firefox/i.test(UA),
isAndroidBrowserOld = isAndroidBrowser && parseFloat(/android ([\d\.]+)/i.exec(UA).pop()) < 4.3,
isAndroid2 = isAndroidBrowser && /android 2\.\d/i.test(UA),
isAndroidChrome = isAndroid && /chrome/i.test(UA),
isKindleFire = /KF[A-Z]{2,3}/.test(UA),
isFirefox = /firefox/i.test(UA),
isIE11 = /Trident/i.test(UA),
isIE = /msie \d/i.test(UA) || isIE11,
isMSTouch = (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0),
isMSTouchPrefix = !!navigator.msMaxTouchPoints,
isPhone = ((/mobile/i.test(UA) && !/ipad|tablet/i.test(UA)) || matchMedia('only screen and (max-device-width : 767px)').matches) && !isKindleFire,
isTablet = (isAndroid && !isPhone) || (isIOS && !isPhone) || isKindleFire,
isMobile = isPhone || isTablet;

this.isPhone = isPhone;
this.isTablet = isTablet;


Thanks in advance for any help

Answer

In general

  • Regexes can be used using java.util.regex.Pattern, Java has no language level support for them like JavaScript
  • Remove the // around the regex, this is part of the JavaScript regex integration
  • any \ will need escaping as \\ within Java strings
  • /i insensitive is equivalent to Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
  • Core regex should be same in 99% of cases

Example

String UA = "iphone";

boolean isIOS = 
        Pattern.compile("ip(hone|od|ad)", Pattern.CASE_INSENSITIVE).matcher(UA).matches();
boolean isSafari5 = 
        Pattern.compile("(mac os x).*version\\/\\d(.\\d)+ (mobile\\/\\w{5,} )?safari", Pattern.CASE_INSENSITIVE).matcher(UA).matches();

System.out.println(isIOS);