regex - Regular expression when reading files javascript -


i have situation have 3 font files , read content in order find mathes font name. thing font names wingdings, wingdings 2, wingdings 3. , when have wingdings font name matches 3 files, need file associated font name, not 3 of them. tried find using indexof method, didn't help. rational way use regular expression, cannot think of right one. 1 more thing need mentioned have pass parameter regexp,

var regexp = new regexp('\\^' + fontname + '$\\', 'g'); if (currentfilecontent.search(regexp) !== -1) {...} 

any appreciated.

it seems try use regex delimiters in regexp constructor. need /.../ in literal notation.

note need not escape start , end of string anchors, lose special meaning in regex then. \\ matches single \, cannot matched after end of string ($).

also, can use regexp#test() function check if string matches pattern (note no g modifier can used it):

var regexp = regexp('^' + fontname + '$');  if (regexp.test(currentfilecontent)) { ... } 

if font names contain special characters, use escaperegexp function mdn:

function escaperegexp(string){   return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } 

and then

var regexp = regexp('^' + escaperegexp(fontname) + '$');  

and final note: if font names appear inside larger string, , need match windings not windings3, use

var regexp = regexp('\\b' + escaperegexp(fontname) + '\\b');  

the \b word boundary.

update

to make sure match font name is not followed whitespace (if any) , digit, use (?!\\s*\\d) lookahead when declaring regexp:

var fontname = "wingding";  var contents = "font name: wingding, other file: font name: wingding 2. , forth. ";  var rexp = regexp(fontname + '(?!\\s*\\d)');  if (rexp.test(contents)) {     document.write(fontname + " found in '<i>" + contents + "</i>'.");  }


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -