简体   繁体   中英

how to match other languages words with regex

Replace words in a Greek given text, for example with English words.

Here an example:

 var str= "Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι."

function findword(){
  word = new RegExp("\\b(προσπάθεια)\\b","gi")
  var sust = str.replace(word,'effort');
}

It should return: "Ενώ Gallant δεν λειτουργεί στην effort να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.

Trying to do it in JavaScript I failed, but I have read that this is not possible since this language does not handle Unicode characters other than English. The only possibility I found is xregexp, but it seems that only would work to detect character classes and not individual words. ¿Is really impossible to make it work in JavaScript?

The Python 3 Documentation states that this language can handle unicode characters, but in this case it seems that it's necessary to write characters with the unicode code... With which languaje would it be possible to replace words in the simplest way as I wrote in the code? Python, Java, Perl ...?

This should do it:

'Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.'.replace( /(προσπάθεια)/g, 'effort' )

Edit

I think this does exactly what you want:

String.prototype.translate = function translate( greek, english ) {
  return this.replace( new RegExp( '(' + greek + ')' ), english );
}

var translatedString = 'Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.'.translate( 'προσπάθεια', 'effort' );
console.log( translatedString );

Perl has exceptional unicode handling. Eg the following code:

use 5.016;
use warnings;
use utf8;
use open qw(:std :utf8);

my $str= "Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.";
$str =~ s/\bπροσπάθεια\b/effort/g;
say $str;

prints

Ενώ Gallant δεν λειτουργεί στην effort να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM