Javascript Question

Select a line that starts with one word (javascript)

I want to build two regular expressions that select :


  1. Lines starting with 'religion'. I try
    /^religion/g
    But I
    dont have results

  2. Match dates and content. For example:
    867.1.1 = {b_reykjavik = tb_shipyard_1}

    I try
    \d{3}\.([1-12])\.([1-31]) = {
    This selects
    867.1.1 = {
    .
    Now, how can I select the other chars untill
    }
    ? Example: https://www.debuggex.com/r/GloZ8dZDVLJ5jc29



The text is:

# 1 - Vestisland
b_reykjavik = tribal
#b_alftanes = city
#b_skalholt = temple
#b_pingvellir = castle
#b_kjalarnes = castle
#b_hvamm = castle
#b_hlidarendi = castle
#b_borg = castle
# Misc
culture = norse
religion = zoroastrian
terrain = arctic

# History
867.1.1 = {
b_reykjavik = tb_shipyard_1
}
900.1.1 = {
b_reykjavik = castle
b_reykjavik = ca_shipyard_1
b_alftanes = city
}
1000.1.1 = {
culture = norwegian
religion = zoroastrian = sunni = catholic
}

Answer

You may use

/^(?:religion.*|\d+(?:\.\d+){2} = {[^}]*})/gm

See Debuggex Demo

Details:

  • ^ - start of a line (since m modifier makes ^ match at the start of a line)
  • (?:religion.* - Alternative 1: religion followed with any 0+ chars other than line break chars
  • | - or
  • \d+(?:\.\d+){2} = {[^}]*}) - 1+ digits, followed with 2 sequences of a . + one or more digits (see \d+(?:\.\d+){2}), then space, =, space, {, zero or more chars other than } (see [^}]*) and a }.

To only grab parts of those records, use capturing groups ((...)) around those subpatterns, see the following regex:

/^(?:religion = (.*)|\d+(?:\.\d+){2} = {([^}]*)})/gm
                ^  ^                    ^     ^

var rx = /^(?:religion = (.*)|\d+(?:\.\d+){2} = {([^}]*)})/gm;
var str = "# 1 - Vestisland\n\n# County Title\ntitle = c_vestisland\n\n# Settlements\nmax_settlements = 2\nb_reykjavik = tribal\n\n#b_alftanes = city\n#b_skalholt = temple\n#b_pingvellir = castle\n#b_kjalarnes = castle\n#b_hvamm = castle\n#b_hlidarendi = castle\n#b_borg = castle\n\n# Misc\nculture = norse\nreligion = zoroastrian\nterrain = arctic\n\n# History\n867.1.1 = {\n	b_reykjavik = tb_shipyard_1\n}\n900.1.1 = {\n	b_reykjavik = castle\n\n	b_reykjavik = ca_shipyard_1	b_alftanes = city\n}\n1000.1.1 = {\n	culture = norwegian\n	religion = zoroastrian = sunni = catholic\n}";
console.log(str.match(rx));