Home > Enterprise >  React Native: Why does a valid Javascript regex pattern not work on Android?
React Native: Why does a valid Javascript regex pattern not work on Android?

Time:12-12

Here is a regex:

const pattern = /\d \s*\.\s*((. ?\n) ?(?=[aA]\)))/;
const str = `8. X-XIII asrlarda barpo etilgan inshootlar to‘g‘ri berilgan qatorni aniqlang.
1) Ismoil Somoniy maqbarasi, 2) Masjidi Kalon,
3) Namozgoh, 4) Minorayi Kalon, 5) Vobkent minorasi, 6) Ahmad Yassaviy maqbarasi, 7) Jarqo‘rg‘on minorasi, 8) Kaltaminor.
A) 1, 2, 3, 6, 7
B) 1, 3, 4, 5, 7
C) 1, 2, 4, 6, 8
D) 2, 3, 4, 6, 7`

const m = pattern.exec(str);
console.log(m) // outputs null when run on Android

Here is the exact same thing running on a browser console:

const pattern = /\d \s*\.\s*((. ?\n) ?(?=[aA]\)))/;
const str = `8. X-XIII asrlarda barpo etilgan inshootlar to‘g‘ri berilgan qatorni aniqlang.
1) Ismoil Somoniy maqbarasi, 2) Masjidi Kalon,
3) Namozgoh, 4) Minorayi Kalon, 5) Vobkent minorasi, 6) Ahmad Yassaviy maqbarasi, 7) Jarqo‘rg‘on minorasi, 8) Kaltaminor.
A) 1, 2, 3, 6, 7
B) 1, 3, 4, 5, 7
C) 1, 2, 4, 6, 8
D) 2, 3, 4, 6, 7`

const m = pattern.exec(str);
console.log(m)

I assume react native is failing to compile my javascript pattern to native code. What am I missing?

dev environment

  • Android 10 Q API 29
  • Windows 10 Pro
  • expo managed react-native app
  • expo: 4.13.0
  • react-native: 0.64.3

CodePudding user response:

It appears the line endings in the target environment are CRLF.

In an ECMAScript regex flavor, a . by default does not match carriage return symbols. So, \n is not enough to match a line break.

There are several ways to fix this issue. You can modify your current regex to make sure you match CRLF/LF/CR line endings:

/\d \s*\.\s*((?:. (?:\r\n?|\n))*?(?=[aA]\)))/

See this regex demo. Here, (?:\r\n?|\n) matches CR and an optional LF char sequence, or a single LF char.

Or, you may just match any zero or more chars:

/\d \s*\.\s*([\w\W]*?)(?=[aA]\))/

See this regex demo.

Note I replaced the ? with *?, just in case there can be empty values between the number with a dot and a). The [\w\W]*? is a common workaround to match any zero or more chars.

  • Related